我正在将 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());
这是例子。看起来所有内容都包含在字符串格式中,当我打印日期时两者显示相同,但是当我比较对象或以二进制格式打印日期时,我看到了差异。我觉得很奇怪,你能解释一下这是怎么回事吗?
这是上面代码的输出。
-8588633131198276118
634739049656490000
最佳答案
你应该使用 roundtrip
format specifier "O" or "o"如果您想保留 DateTime
的值。
The "O" or "o" standard format specifier represents a custom date and time format string using a pattern that preserves time zone information. For DateTime values, this format specifier is designed to preserve date and time values along with the DateTime.Kind property in text. The formatted string can be parsed back by using the DateTime.Parse(String, IFormatProvider, DateTimeStyles) or DateTime.ParseExact method if the styles parameter is set to DateTimeStyles.RoundtripKind.
使用您的代码(除了更改格式字符串):
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());
我得到:
-8588633127598789320
-8588633127598789320
关于c# - 将 C# 日期时间转换为字符串并返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10798980/