DateTime truncation

J

JezB

I want to compare two DateTime values but only down to seconds, so how do I
truncate DateTime values to second granularity ?
Similarly, I may want to truncate to the minute granularity.
I also may want to round to the nearest minute.

How do I do these things ? I'm sure it must be really simple but I cant find
anything in the DateTime class. I know I can convert to a numeric date and
time format and do a string compare but I imagine this is a very inefficient
way to do it.
 
J

Jon Skeet [C# MVP]

JezB said:
I want to compare two DateTime values but only down to seconds, so how do I
truncate DateTime values to second granularity ?
Similarly, I may want to truncate to the minute granularity.
I also may want to round to the nearest minute.

How do I do these things ? I'm sure it must be really simple but I cant find
anything in the DateTime class. I know I can convert to a numeric date and
time format and do a string compare but I imagine this is a very inefficient
way to do it.

The easiest way is just to create a new DateTime, specifying the bits
you're interested in, if you see what I mean.
 
J

JezB

By calling the Year, Month, Day, Hour, Minute and Second methods on both
DateTime's ?? Seems a bit over the top ! I'm surprised there's no Trunc or
Round method built in to the framework.
 
J

Jon Skeet [C# MVP]

JezB said:
By calling the Year, Month, Day, Hour, Minute and Second methods on both
DateTime's ?? Seems a bit over the top !

No, by using the constructor which takes lots of parameters:

DateTime truncated = new DateTime (old.Year, old.Month, old.Day,
old.Hour, old.Minute, old.Second);
(or whatever).
I'm surprised there's no Trunc or Round method built in to the framework.

Agreed, it would be handy sometimes.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top