Hector
Hector

Reputation: 21

What is the best way to get rid of milliseconds from DateTime?

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.

Upvotes: 1

Views: 1484

Answers (5)

David
David

Reputation: 387

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);

Upvotes: 0

Heinzi
Heinzi

Reputation: 172380

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.

Upvotes: 6

Behzad F94
Behzad F94

Reputation: 198

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

Upvotes: -1

Amit Verma
Amit Verma

Reputation: 2490

DateTime dt = new DateTime();
dt = Convert.ToDateTime("2021 - 06 - 23T12: 30:40z");

var ss = dt.ToString("yyyy-MM-dd hh:mm:ss");

Upvotes: -1

Jortx
Jortx

Reputation: 727

var date = DateTime.Now;
date = new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Kind);

Upvotes: 0

Related Questions