0

When I have a DateTime value with 500 milliseconds or more, I would expect the ToString method to round to the nearest second (if the current culture is showing seconds, which en-US does). However, it instead seems to truncate the millisecond value

For example, the code below outputs this: 10/1/2010 8:22:33 AM, when I expect it to output this: 10/1/2010 8:22:34 AM.

var d = new DateTime(2010, 10, 1, 8, 22, 33, 777);
string date = d.ToString(new CultureInfo("en-US"));
MessageBox.Show(date);

Note I am aware that I can give a custom format string to ToString, but I don't want to do this because I will actually be passing the current culture to ToString and not always passing the en-US

I am trying to reconcile values with an existing system (Excel) that does round the values. On a machine with US locale, if you paste 2010/10/1 8:22:33.777 in a cell with General number format and then click the cell, the formula bar in excel will show you 10/1/2010 8:22:34 AM

tjsmith
  • 729
  • 7
  • 21
  • 1
    @tttmack Could you add 500 (or 499) ms before converting to string? – AlexD Sep 11 '15 at 00:24
  • 3
    Why would it round time up? That would be like time travelling, but with a CLR instead of a flux capacitor! – Glen Thomas Sep 11 '15 at 00:26
  • 1
    Rounding up is bad practice and quickly leads to funky edge case bugs! – FiringSquadWitness Sep 11 '15 at 00:26
  • The referenced old question (at top) didn't really provide the answer. I've added the answer: _The reason for not rounding is, that_ `ToString` _just prints the date/time parts you ask for._ [Why ToString doesn't round](http://stackoverflow.com/a/32517569/3527297) – Gustav Sep 11 '15 at 07:13

0 Answers0