Showing posts with label DateTime. Show all posts
Showing posts with label DateTime. Show all posts

A cautionary tale, always be careful with your DateTime manipulations (or how I showed the Internet I was an idiot)

Posted on: Friday, 12 December 2014 18:00

A couple of silly mistakes I made while working with `DateTime` object manipulations. Its a short read and hopefully you will remember my folly the next time you need to tweak your dates.

Round off time to the nearest minute

Posted on: Thursday, 17 September 2009 07:59

Say you have a DateTime object like this:

DateTime someTime = DateTime.Parse("00:00:38");

Rounding Up

How would you round this up to the nearest minute? There isn't a built in function to do this so you have to use a little bit of maths to get there. There are 60 seconds in a minute. We already have 38 seconds on the clock. So we need to add on 60 - 38 = 22 more seconds.

In code this looks like:

DateTime RoundUp = DateTime.Parse("00:00:38");
RoundUp = RoundUp.AddSeconds(60 - RoundUp.Second);

Now our RoundUp contains "00:01:00".

Rounding Down

To round down we use the same idea:

DateTime RoundDown = DateTime.Parse("00:01:38");
RoundDown = RoundDown.AddSeconds(-RoundDown.Second);

Note

The AddSeconds() method doesn't actually alter the DateTime its working on - it just returns a new one. This is why I assigned the DateTime to itself in the examples above.