当你有一个格式为UTC时间的string
时,如何将其格式化为DateTime
但当地时间?
例如,如果我有以下代码,它会不正确地格式化我的代码(意味着错误的时间)
string dateformatted = "2017-01-10T11:13:00-07:00"
DateTime.Parse(Convert.ToString(dateformatted));
但是,这个输出是
01/10/2017 1:13:00 PM
比实际时间11:13:00提前2小时。如何将字符串转换为适当的时区时间?
答案 0 :(得分:3)
我相信您正在寻找Parse
方法的Parse(String, IFormatProvider, DateTimeStyles)重载。第三个参数DateTimeStyles
将允许强制或禁止本地和UTC时间之间的转换。 Options包括:AdjustToUniversal
,AssumeLocal
和AssumeUniversal
(以及其他)。
答案 1 :(得分:2)
根据MSDN docs:
返回值类型:DateTime
一个对象,它等同于s中包含的日期和时间。 通常,Parse方法返回其Kind的DateTime对象 属性为 DateTimeKind.Unspecified 。但是,Parse方法 也可以执行时区转换并设置种类的值 属性不同,取决于s和样式的值 参数:
如果:
+-------------------------------------------------------------------------------------------+---------------------------------------------------------------------+--------------------+
| If | Time zone conversion | Kind property |
+-------------------------------------------------------------------------------------------+---------------------------------------------------------------------+--------------------+
| s contains time zone information. | The date and time is converted to the time in the local time zone. | DateTimeKind.Local |
+-------------------------------------------------------------------------------------------+---------------------------------------------------------------------+--------------------+
| s contains time zone information, and styles includes the AdjustToUniversalflag. | The date and time is converted to Coordinated Universal Time (UTC). | DateTimeKind.Utc |
+-------------------------------------------------------------------------------------------+---------------------------------------------------------------------+--------------------+
| s contains the Z or GMT time zone designator, and styles includes the RoundtripKind flag. | The date and time are interpreted as UTC. | DateTimeKind.Utc |
+-------------------------------------------------------------------------------------------+---------------------------------------------------------------------+--------------------+
您应该添加时区。