获取时区的日期时间偏移 [英] Get Datetime Offset for Timezone

查看:92
本文介绍了获取时区的日期时间偏移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码,需要找到中欧时区UTC的当前偏移量.

I have a code where I need to find current offset from UTC for Central European Timezone.

我的代码已部署在azure应用服务中.

My code is deployed in azure app service.

var offset = DateTimeOffset.Now.Offset.Hours + ":" + 
             DateTimeOffset.Now.Offset.Minutes;

上述代码的问题在于,它取决于服务器时间,即使我的App Service在西欧,Azure App Service的时区也始终是UTC.

The problem with above code is, it relies on server time, Even though my App Service is in West Europe, the time zone of Azure App Service is always UTC .

一种解决方案是将Azure App Service TimeZone更改为所需的TimeZone,它可以工作,但是我也希望使用代码来获取偏移量.

One solution is to change Azure App Service TimeZone to Desired TimeZone and it will work, but i am also looking at getting the offset using code.

请记住,我无法使用系统日期时间来获取偏移量,因为它始终是UTC.

Remember I cannot use system datetime to get offset as it's always UTC.

无论系统日期时间如何,我都可以获得当前中欧的DatetimeOffset吗?

Can I get Current Central Europe DatetimeOffset irrespective of system date time?

推荐答案

您可以执行以下操作

TimeZoneInfo cet = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");

DateTimeOffset offset = TimeZoneInfo.ConvertTime(DateTime.Now, cet);

此处所述.

如果不确定 TimeZoneId ,则可以使用

If you're not sure about a TimeZoneId you can use GetSystemTimeZones() to find it.

所述,在这里,将要做这样的事情

DateTime nowCet = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.Now, 
    "Central European Standard Time");

这样做的好处是,您可以轻松计算出两个时区之间的时差,例如

The nice thing about this is you can easily calculate the difference between two time zones like, for example

DateTime newYork = new DateTime(2017, 10, 04, 12, 23, 00);
DateTime berlin = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(newYork, 
    "Eastern Standard Time", "Central European Standard Time");

TimeSpan diff = berlin - newYork;

这篇关于获取时区的日期时间偏移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆