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

标签 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());

这是例子。看起来所有内容都包含在字符串格式中,当我打印日期时两者显示相同,但​​是当我比较对象或以二进制格式打印日期时,我看到了差异。我觉得很奇怪,你能解释一下这是怎么回事吗?

这是上面代码的输出。

-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/

相关文章:

c# - 使用 IModelBinder 自定义模型绑定(bind)

c# - 传递基本类型集合时,C#方法选择选择对象而不是IEnumerable <object>

java - java字符串中的西类牙字符问题

python - 从 PySpark 的 RDD 中的数据中查找最小和最大日期

ruby - 有没有办法获取本地时区的 TZInfo 样式字符串?

javascript - 从 C# 为 javascript 变量赋值

c# - DateTime.TryParseExact 与 "U"和 DateTimeStyles.AdjustToUniversal

swift - 如何计算 Swift 中不包括新行的字符?

ruby - 如何在 Ruby 中拆分字符串?

python - 从 dtype ('O' ) 转换为 datetime 的问题