如何转换服务器时间为当地时间 [英] how to convert server time to local time

查看:181
本文介绍了如何转换服务器时间为当地时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有时间
我的服务器是在美国,我在丹麦(欧洲),我想有我的网站显示在我的本地的时间。我该怎么做?

I have a problem with time
My server is in the USA and I'm in Denmark (Europa) and I would like to have my site show the time in my local time. How can I do that?

我试试这个

Datetime localtime = DateTimeOffset.Now.ToOffset(new TimeSpan(1,0,0)).DateTime;

和它的作品,但是当我在GMT + 1 / UTC + 1,当我不是GMT + 2 / UTC + 2时才会有效。
是否有这样做的另一种方式 - 做一个简单的方法

and it works, but it will only work when I'm in GMT+1 / UTC+1 and not when I'm in GMT+2 / UTC+2. Is there another way of doing this - a simpler way of doing it?

推荐答案

你应该做的是如下的唯一方式:

The only way you should do it is as follows:

string zoneId = "Central European Standard Time";
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
DateTime result = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow,tzi);
Console.WriteLine("Time is " + result + " in Denmark");

使用的TimeZoneInfo类是在.NET中的唯一可靠的方法转换到/从不同的时区,并得到适当的DST转换。

Using the TimeZoneInfo class is the only reliable way in .Net to convert to/from different timezones AND get proper DST conversions.

TimeZoneInfo.ConvertTimeToUtc(dtLocal,奥兹)是反向从本地时间转换为UTC时间。

TimeZoneInfo.ConvertTimeToUtc(dtLocal,tzi) is the reverse converting from a local time to a utc time.


有关的区ID字符串,您可以在这里运行code的位...

For the TimeZone Id strings, you can run the bit of code here...

foreach( var tz in TimeZoneInfo.GetSystemTimeZones() )
{
    Console.WriteLine(tz.DisplayName + " is Id=','" + tz.Id + "'");
}

这篇关于如何转换服务器时间为当地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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