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

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

问题描述

我有时间问题

我的服务器在美国,我在丹麦(欧罗巴),我想让我的网站在当地时间显示。我该怎么做?

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?

推荐答案

如下:

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,tzi)是从本地时间到utc time。

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

对于TimeZone Id字符串,您可以在这里运行一些代码...

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天全站免登陆