1

When I get DateTime from the database, it returns 2021-06-23T12:30:40.1234564z but what I want is 2021-06-23T12:30:40z. What is the best way to get rid of the milliseconds here? Thanks.

Hector
  • 21
  • 4
  • use a formatter withoput milliseconds – ΦXocę 웃 Пepeúpa ツ Jun 30 '21 at 08:54
  • @ΦXocę웃Пepeúpaツ: That will return a string, not modify the original DateTime. I have needed the latter in the past a few times (for example, when comparing a value with a value stored somewhere where milliseconds are lost: the WebForms ViewState or certain database systems). Or [this OLEDB bug](https://stackoverflow.com/q/6253906/87698). – Heinzi Jun 30 '21 at 09:03

5 Answers5

6

Personally, I use this:

dt = dt.Subtract(new TimeSpan(0, 0, 0, 0, dt.Millisecond));

It's a little more verbose than the Ticks-Modulo-Trickery that can be used instead, but I like its readability: It's immediately obvious what the code does.


As JonSkeet suggested in the comments, this is more compact and equally readable:

dt = dt.AddMilliseconds(-dt.Millisecond);

I like it even better than my solution, since in my solution a hard-to-spot bug can easily be introduced by forgetting one of the 0 parameters.

Heinzi
  • 167,459
  • 57
  • 363
  • 519
0
var date = DateTime.Now;
date = new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);
Jortx
  • 707
  • 1
  • 7
  • 22
0

As an addition to the answer by @jonskeet you could also round

if(dt.millis>500) dt = dt.AddMilliseconds(1000)
dt = dt.AddMilliseconds(-dt.millis);
David
  • 307
  • 3
  • 17
-1
DateTime dt = new DateTime();
dt = Convert.ToDateTime("2021 - 06 - 23T12: 30:40z");

var ss = dt.ToString("yyyy-MM-dd hh:mm:ss");
Amit Verma
  • 2,450
  • 2
  • 8
  • 21
  • This lacks the "T" in the middle and the "Z" at the end, and "hh" is 12-hour time, whereas "HH" is 24-hour time. Also, you might want to call `.ToUniversalTime()` before calling `.ToString(...)` to ensure that it actually is universal time before you format it. – ProgrammingLlama Jun 30 '21 at 09:01
  • @Llama Thanks for the suggestion. Based on your suggestion and my code user can decide. Happy Coding. – Amit Verma Jun 30 '21 at 09:17
  • 1
    Okay, but your "suggestion" isn't what the OP asked for. OP said: _"but what I want is 2021-06-23T12:30:40z."_ - does your solution produce this format? – ProgrammingLlama Jun 30 '21 at 09:17
-1

dt.ToString("YYYYY/MM/DD");

Behzad F94
  • 198
  • 2
  • 5
  • `YYYY` and `DD` don't exist in .NET for formatting datetime values, and even if they did, this lacks the hours, minutes, and seconds. – ProgrammingLlama Jun 30 '21 at 09:01