【发布时间】:2012-06-03 16:00:06
【问题描述】:
我正在将 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
【问题讨论】:
-
小点:如果您要使用
InvariantCulture解析字符串,那么您可能也想将InvariantCulture传递给ToString 方法,只是为了安全起见:now1.ToString(FMT, CultureInfo.InvariantCulture);
标签: c# string datetime data-conversion