When a Double
is formatted as a string rounding is used. E.g.
Console.WriteLine(12345.6.ToString("F0"));
outputs
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));
outputs
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));
outputs
2010-12-31T23:59:59 2011-01-01T00:00:00
Usually we display time in in 12 hour format hh:mm:aa format (e.g. 12:30 PM) or 24 hour format HH:mm (e.g. 13:30), however sometimes we also want to show the milliseconds in the time. To show the milliseconds in the time we include “SSS” in the pattern which displays the Milliseconds.
You can add milliseconds by adding SSS at the end, such as the format will be HH:mm:ss. SSS .
A date and time format string defines the text representation of a DateTime or DateTimeOffset value that results from a formatting operation. It can also define the representation of a date and time value that is required in a parsing operation in order to successfully convert the string to a date and time.
To display the millisecond component of a DateTime valueParse(String) or DateTimeOffset. Parse(String) method. To extract the string representation of a time's millisecond component, call the date and time value's DateTime.
This is a bit subjective, but I would say that rounding date and times values as opposed to truncating them would result in a "more" unexpected behavior.
For example, rounding new DateTime(2011, 1, 1, 23, 59, 59, 999)
would result in a new day completely. This sounds much more weird than just truncating the value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With