将C#日期时间转换为字符串并返回

axe*_*axe 27 c# string datetime data-conversion

我正在将C#日期时间转换为字符串.后来当我将它转换回DateTime对象时,看起来它们并不相同.

const string FMT = "yyyy-MM-dd HH:mm:ss.fff";
DateTime now1 = DateTime.Now;
string strDate = now1.ToString(FMT);
DateTime now2 = DateTime.ParseExact(strDate, FMT, CultureInfo.InvariantCulture);
Console.WriteLine(now1.ToBinary());
Console.WriteLine(now2.ToBinary());
Run Code Online (Sandbox Code Playgroud)

这是一个例子.看起来一切都包含在字符串格式中,当我打印日期时两者显示相同,但​​是当我比较对象或打印日期的二进制格式时,我看到了差异.这对我来说很奇怪,你能解释一下这里发生了什么吗?

这是上面代码的输出.

-8588633131198276118
634739049656490000
Run Code Online (Sandbox Code Playgroud)

Ode*_*ded 40

如果要保留值,则应使用roundtrip格式说明符"O"或"o"DateTime.

"O"或"o"标准格式说明符使用保留时区信息的模式表示自定义日期和时间格式字符串.对于DateTime值,此格式说明符旨在保留日期和时间值以及文本中的DateTime.Kind属性.如果styles参数设置为DateTimeStyles.RoundtripKind,则可以使用DateTime.Parse(String,IFormatProvider,DateTimeStyles)或DateTime.ParseExact方法解析格式化的字符串.

使用您的代码(除了更改格式字符串):

const string FMT = "O";
DateTime now1 = DateTime.Now;
string strDate = now1.ToString(FMT);
DateTime now2 = DateTime.ParseExact(strDate, FMT, CultureInfo.InvariantCulture);
Console.WriteLine(now1.ToBinary());
Console.WriteLine(now2.ToBinary());
Run Code Online (Sandbox Code Playgroud)

我明白了:

-8588633127598789320
-8588633127598789320
Run Code Online (Sandbox Code Playgroud)

  • 我在使用这种方法时遇到了 UTC 日期问题。请参阅下文了解我是如何修复它的。 (2认同)

Tay*_*ere 8

Oded的答案很好,但是对于UTC日期它并不起作用.为了使其适用于UTC日期,我需要指定DateTimeStyles值"RoundtripKind",以便它不会尝试假设它是本地时间.以下是上面的更新代码:

const string FMT = "O";
DateTime now1 = DateTime.Now;
string strDate = now1.ToString(FMT);
DateTime now2 = DateTime.ParseExact(strDate, FMT, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
Console.WriteLine(now1.ToBinary());
Console.WriteLine(now2.ToBinary());
Run Code Online (Sandbox Code Playgroud)

请注意,这适用于UTC和本地日期.