Reputation: 21
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
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
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
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
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