c# - 为什么将 DateTime 格式化为字符串会截断而不是舍入毫秒?

标签 c# .net datetime rounding truncate

Double 被格式化为字符串舍入时。例如

Console.WriteLine(12345.6.ToString("F0"));

输出

12346

However, when a DateTime is formatted as a string truncation is used. E.g.

var ci = CultureInfo.InvariantCulture;
var dateTime = DateTime.Parse("2011-09-14T15:18:42.999", ci);
Console.WriteLine(dateTime.ToString("o", ci));
Console.WriteLine(dateTime.ToString("s", ci));
Console.WriteLine(dateTime.ToString("yyyy-MM-hhThh:mm:ss.f", ci));

输出

2011-09-14T15:18:42.9990000
2011-09-14T15:18:42
2011-09-14T15:18:42.9

What is the reasoning (if any) behind this behavior?


Rounding to nearest second can be achieved by adding half a second before formatting as a string:

var ci = CultureInfo.InvariantCulture;
var dateTime = DateTime.Parse("2010-12-31T23:59:59.999", ci);
Console.WriteLine(dateTime.ToString("s", ci));
var roundedDateTime = dateTime.AddMilliseconds(500);
Console.WriteLine(roundedDateTime.ToString("s", ci));

输出

2010-12-31T23:59:59
2011-01-01T00:00:00

最佳答案

这有点主观,但我会说舍入日期和时间值而不是截断它们会导致“更多”意外行为。

例如,四舍五入 new DateTime(2011, 1, 1, 23, 59, 59, 999) 将完全是新的一天。这听起来比仅仅截断值要奇怪得多。

关于c# - 为什么将 DateTime 格式化为字符串会截断而不是舍入毫秒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7417040/

相关文章:

c# - Image.FromFile 为什么读取位图比读取 jpeg 文件快

c# - WP中的MVVM和枢轴控制

c# - “System.Windows.Forms.Timer”无法解析

c# - 在 Azure 辅助角色中读取/写入临时文件

python - 创建包含月份中的天数的列表

c# - 在 WinForms 之间传递数据时遇到问题

c# - Xamarin 表单 - 切换条目 View 的 IsPassword 时出错(仅在 uwp 上)

C# 国际奥委会 : Implementing conditional injection

c# - 如何将 DateTime 转换为该月的最后一天?

sql - 如何在 PostgreSQL 字符串中的单引号后添加分号?