Skip to main content
 首页 » 编程设计

c#之如何根据时区解析日期和时间

2024年02月06日16java哥

我想把字符串解析成时间。

string inputDate = "1970-01-01T00:00:00+0000";  
var dt = DateTime.Parse(inputDate, CultureInfo.InvariantCulture);   
Console.WriteLine("Date==> " + dt); 

它在印度时间(UTC +5.30)工作正常。

但是当我在模拟器的设置中将时区更改为 UTC -5 时,输出显示

12/31/1969 7:00:00 PM 

当我在设置中更改时区时,日期应该相同。请帮我解决我的问题。

请您参考如下方法:

让我解释一下这是怎么回事..

通常,DateTime.Parse方法返回 DateTime 的 Kind属性(property)将是Unspecified .

但由于您的字符串包含时区信息,并且您使用 DateTime.Parse 方法而不使用 DateTimeStyles重载(它默认使用 DateTimeStyles.None),您的 DateTime 的 Kind 属性将是 Local。

这就是为什么当您在 UTC +05.30 时区系统中使用您的代码时,它会生成如下结果;

01/01/1970 05:00:00 AM 

当你使用UTC -05.00时区系统时,它会生成;

12/31/1969 7:00:00 PM // which is equal 12/31/1969 19:00:00 AM representation 

这太正常了。

The date should be same when ever i change the time zone in settings.

将您的DateTime设为UTC是这种情况下的最佳选择。使用ToUniversalTime()方法是在 Local 时间内执行此操作的一种方法。

来自文档;

The Coordinated Universal Time (UTC) is equal to the local time minus the UTC offset.

由于您的代码生成Local 时间,因此您的ToUniversalTime() 生成的日期时间在两个时区都相同。

另一种方法,使用 DateTimeStyles.AdjustToUniversal 作为 DateTime.Parse 方法中的第三个参数。

来自文档;

Date and time are returned as a Coordinated Universal Time (UTC). If the input string denotes a local time, through a time zone specifier or AssumeLocal, the date and time are converted from the local time to UTC. If the input string denotes a UTC time, through a time zone specifier or AssumeUniversal, no conversion occurs. If the input string does not denote a local or UTC time, no conversion occurs and the resulting Kind property is Unspecified.

string inputDate = "1970-01-01T00:00:00+0000"; 
var dt = DateTime.Parse(inputDate, 
                        CultureInfo.InvariantCulture, 
                        DateTimeStyles.AdjustToUniversal); 

这将生成 01/01/1970 00:00:00,Kind 是 Utc。