将本地客户端系统时间转换为CST时间,反之亦然。

3

我需要将日期时间存储在CST时区,无论给定的时区为何。

访问该应用程序的客户来自各种不同的时区,如IST、CST、EST等。

我需要将客户输入的所有日期时间都存储在CST时区中,并在检索时将其转换回他们的本地时区。

如何实现?

3个回答

2

像这样的代码可能适合您。我可能对时区id的值有误,但我认为这很接近。时区相关的内容在.NET 3.5+中可用。

DateTime clientDateTime = DateTime.Now;
        DateTime centralDateTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(clientDateTime, "Central Time (US & Canada)");

编辑:

如果您能够通过检测客户端时区来存储UTC日期时间,那将是最佳选择。然后根据客户端时区,您可以按照客户端的本地时区呈现日期。


2
这最终对我抛出了一个异常。使用 TimeZoneInfo.ConvertTimeBySystemTimeZoneId(date,"Central Standard Time") 就解决了问题。 - CountMurphy

2

一般认为在数据库中存储所有日期时间值时应使用GMT / UTC格式。

对于那些想要将UTC值呈现为特定时区的不同应用程序用户,建议像wilpeck提到的那样确定最终用户的语言环境并:

  • 持久化时,与UTC日期值一起存储语言环境
  • 读取时,使用相关的语言环境值将UTC值呈现为本地时间

编辑:

例如:

您可能有一个带有字段StartDateTime的表,为支持多个时区,您可能还有一个额外的字段StartDateTimeOffset。如果客户端位于印度标准时间(IST)区域,则可能具有2009/10/13 14:45的日期时间值,该值为UTC时间的2009/10/13 09:15。因此,您将存储UTC值(2009/10/13 09:15)在字段StartDateTime中,并在字段StartDateTimeOffset中存储偏移量+05:30。现在,当您从数据库中读取此值时,可以使用偏移量将UTC日期时间值(2009/10/13 09:15)转换回本地时间2009/10/13 14:45。


我可以有一个样本吗?例如:客户端系统在IST,服务器在CST。 - Prasad
谢谢 cottsak,这非常有用。 - Prasad

1
尝试像这样。
DateTime clientDateTime = DateTime.Now;
DateTime centralDateTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(clientDateTime, "Central Standard Time");

时区ID
DateTime currentTime = DateTime.Now;
Console.WriteLine("Current Times:");
Console.WriteLine();
Console.WriteLine("Los Angeles: {0}", 
                  TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Pacific Standard Time"));
Console.WriteLine("Chicago: {0}", 
                  TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Central Standard Time"));
Console.WriteLine("New York: {0}", 
                  TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Eastern Standard Time"));
Console.WriteLine("London: {0}", 
                  TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "GMT Standard Time"));
Console.WriteLine("Moscow: {0}", 
                  TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Russian Standard Time"));
Console.WriteLine("New Delhi: {0}", 
                  TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "India Standard Time"));
Console.WriteLine("Beijing: {0}", 
                  TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "China Standard Time"));
Console.WriteLine("Tokyo: {0}", 
                  TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentTime, TimeZoneInfo.Local.Id, "Tokyo Standard Time"));

https://learn.microsoft.com/en-us/dotnet/api/system.timezoneinfo.converttimebysystemtimezoneid?view=netcore-3.1

https://www.c-sharpcorner.com/blogs/how-to-convert-a-datetime-object-into-specific-timezone-in-c-sharp


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接