gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:07:09 25 4
gpt4 key购买 nike

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.99900002011-09-14T15:18:422011-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:592011-01-01T00:00:00

最佳答案

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

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com