1

Currently I'm using this:

new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day,
             DateTime.Now.Hour, DateTime.Now.Minute, 0)

Is there any other way to directly set seconds and milliseconds to 0.

vc 74
  • 37,131
  • 7
  • 73
  • 89
svvc
  • 33
  • 7

1 Answers1

6

Your current code is dangerous, as you're evaluating DateTime.Now multiple times. The current time can change between two calls, so you could end up with inconsistent values. It would be better as:

// Do you *definitely* want the current date/time in the system  local time zone?
// Might be correct for local client apps; almost certainly not for server-side code.
DateTime now = DateTime.Now;
DateTime rounded = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0);

That's not too bad. Another alternative would be:

DateTime now = DateTime.Now;
DateTime rounded = now.Date + new TimeSpan(now.Hour, now.Minute, 0);

If you definitely want to use DateTime, and you definitely want to use the system local time zone, that's probably what I'd do.

As a plug for my Noda Time project, that would be something like:

rounded = now.With(TimeAdjusters.TruncateToMinute);

... but you'd have a lot more options to consider in terms of what type you wanted now to be in the first place.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194