【问题标题】:how to convert server time to local time如何将服务器时间转换为本地时间
【发布时间】:2010-09-24 01:53:00
【问题描述】:

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

我试试这个

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

它有效,但它仅在我处于 GMT+1 / UTC+1 时有效,而在我处于 GMT+2 / UTC+2 时无效。 是否有另一种方法 - 一种更简单的方法?

【问题讨论】:

    标签: asp.net datetime c#-3.0


    【解决方案1】:

    您应该这样做的唯一方法如下:

    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 转换的唯一可靠方法。

    TimeZoneInfo.ConvertTimeToUtc(dtLocal,tzi) 是从本地时间到UTC时间的反向转换。


    对于 TimeZone Id 字符串,您可以在此处运行代码...

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

    【讨论】:

    • 应该注意的是,TimeZoneInfo 也正确地考虑了未来和过去时间的 DST 差异。不要试图使用 BaseUtcOffset 或 GetUtcOffset() 自己进行转换。您还可以使用 TimeZoneInfo 检查无效和不明确的时间。
    • 如果时区未知?对于不同国家的每个人,我们该怎么做?
    • @JhoonBey 允许人们选择他们的国家,或使用根据他们的 IP 地址确定国家的服务。例如stackoverflow.com/q/13921563/14033
    【解决方案2】:

    您可以从服务器中获取时间并执行此操作。

    DateTime myTimeGMT = ServerTime.ToUniversalTime();
    

    这样做:

    DateTime myTimeLocal = myTimeGMT.ToLocalTime();
    

    这里唯一的限制是您所在的计算机必须设置为您要转换到的时区。

    根据我的经验,当 'From' 时间或 'To' 时间都不是本地时区时,.NET 在时区之间转换时遇到问题。

    我希望这会有所帮助。

    【讨论】:

    • 日期时间 myTimeLocal = myTimeGMT.ToLocalTime();这会将其转换回服务器时间
    • 您需要查看 TimeZoneInfo 类以执行转换。您显示的转换不知道 DST 问题。
    【解决方案3】:

    我使用模板字段将转换显示在网格视图中。

    <asp:TemplateField HeaderText="Last Activity">
                    <ItemTemplate>
                        <asp:Label ID="LastActivityLBL" runat="server" Text='<%# Convert.ToDateTime(Eval("LastActivityDate")).ToLocalTime() %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Last Login">
                    <ItemTemplate>
                        <asp:Label ID="LastLoginLBL" runat="server" Text='<%# Convert.ToDateTime(Eval("LastLoginDate")).ToLocalTime() %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
    

    【讨论】:

      【解决方案4】:
      Datetime localtime = DateTimeOffset.Now.ToOffset(new TimeSpan(1,0,0)).DateTime;
      

      你可以改变你的时间跨度像--

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

      根据时区。

      【讨论】:

        猜你喜欢
        • 2011-02-12
        • 1970-01-01
        • 2017-10-08
        • 1970-01-01
        • 2016-07-08
        • 2023-03-31
        • 1970-01-01
        • 2013-04-26
        • 2012-01-26
        相关资源
        最近更新 更多