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

标签 c# string datetime timezone

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

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方法返回 DateTimeKind属性(property)将是Unspecified .

但由于您的字符串包含时区信息,并且您使用 DateTime.Parse 方法而不使用 DateTimeStyles重载(它默认使用 DateTimeStyles.None),您的 DateTimeKind 属性将是 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:00KindUtc

关于c# - 如何根据时区解析日期和时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27199058/

相关文章:

c# - DateTime.AddDays 的准确性如何?

C# DateTime 使用 at ToString() 后进行转换;

c# - 避免在锁内和锁外重复if语句

c - 如何在 ANSI C 中用 NULL 替换字符串中的字符?

c# - 全局异常处理程序是否意味着删除不必要的 try catch block ?

c++ - 将 GetLastError() 转换为带有错误字符串的异常

c - 在 C 中返回字符串的正确方法

php - Mysql 两个日期的天数和分钟结果差异

c# - C# 解决方案资源管理器中的 XML 文件

c# - 将参数设置为 asp.net WebAPI URL