我有一个表单,用户从UI中选择日期。
我从UI中获得以下值
var uiDate = "2019-05-03T00:00:00.000Z".
我需要将其转换为DateTime以进行进一步处理。
var dt = Convert.ToDateTime(uiDate);
dt值为"5/2/2019 8:00:00 dt“。
正如我们所看到的,从UI中选择的日期到DateTime转换后的一天,我总是会得到回复。我正期待着“2019年3月5日”。我无法弄清楚为什么在DateTime转换之后会发生这种情况?
发布于 2019-05-05 13:39:14
Convert.ToDateTime
正在隐式地将值转换为本地时间。如果使用DateTime.ParseExact
,可以指定适当的转换选项:
using System;
using System.Globalization;
class Program
{
static void Main()
{
string text = "2019-05-03T00:00:00.000Z";
DateTime parsed = DateTime.ParseExact(
text, // The value to parse
// The pattern to use for parsing
"yyyy-MM-dd'T'HH:mm:ss.FFF'Z'",
// Use the invariant culture for parsing
CultureInfo.InvariantCulture,
// Assume it's already in UTC, and keep it that way
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
Console.WriteLine(parsed); // 03/05/2019 00:00:00 (on my machine; format will vary)
Console.WriteLine(parsed.Kind); // Utc
}
}
https://stackoverflow.com/questions/55992125
复制相似问题