C# 从本地客户端系统转换';s时间到CST,反之亦然

C# 从本地客户端系统转换';s时间到CST,反之亦然,c#,jquery,asp.net-mvc,timezone,C#,Jquery,Asp.net Mvc,Timezone,我需要在CST时区中存储datetime,而不考虑给定的任何时区 访问应用程序的客户端来自不同的时区,如IST、CST、EST等 我需要将客户端在CST时区中输入的所有日期时间存储到我的数据库中。在检索时,我需要转换回当地时区 如何实现它?像这样的事情很可能适合你。我可能有一个不正确的时区id值,但我认为这是接近。时区信息在.NET3.5中提供+ DateTime clientDateTime = DateTime.Now; DateTime centralDateTime =

我需要在CST时区中存储datetime,而不考虑给定的任何时区

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

我需要将客户端在CST时区中输入的所有日期时间存储到我的数据库中。在检索时,我需要转换回当地时区


如何实现它?

像这样的事情很可能适合你。我可能有一个不正确的时区id值,但我认为这是接近。时区信息在.NET3.5中提供+

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


如果您可以通过检测客户机时区来存储UTC中的DateTime,则无论何时客户机向您提供的日期都是最佳选择。然后,根据客户端时区,可以根据客户端的本地时区呈现日期

通常接受以GMT/UTC格式在数据库中存储所有日期时间值

对于那些希望为应用程序的不同用户(如wilpeck所述)将UTC值呈现到特定时区的用户,建议您确定最终用户的区域设置,并:

  • 持久化时,使用UTC日期值存储区域设置
  • 读取时,使用关联的区域设置值将UTC值呈现为本地时间
编辑:

例如:


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

像这样尝试。

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"));


能给我一个样品吗?例如:客户端的系统在IST,服务器在CST。谢谢cottsak,它非常有用。这最终为我抛出了一个异常。使用TimeZoneInfo.ConvertTimeBySystemTimeZoneId(日期,“中央标准时间”)实现了这一点