Subscribe to CurtisRutland.Write("...");        RSS Feed
-----

DateTime Extension Methods: Floor, Ceiling, and Round

Icon 1 Comments
I came across a thread at StackOverflow when I was looking for a good way to round DateTimes to the nearest given time frame. I thought these were great algorithms, so I modified them a bit to be extension mehtods. Here they are:

public static DateTime Floor(this DateTime date, TimeSpan span) {
    var ticks = date.Ticks / span.Ticks;
    return new DateTime(ticks * span.Ticks);
}

public static DateTime Round(this DateTime date, TimeSpan span) {
    var ticks = (date.Ticks + (span.Ticks / 2) + 1) / span.Ticks;
    return new DateTime(ticks * span.Ticks);
}

public static DateTime Ceiling(this DateTime date, TimeSpan span) {
    var ticks = (date.Ticks + span.Ticks - 1) / span.Ticks;
    return new DateTime(ticks * span.Ticks);
}


Floor will always round a value down to the nearest timeframe. Example: 14:34.Ceil(5 min) would yield 14:30.

Round will round either up or down to the nearest timeframe, depending on which is closer. Example: 14:34.Round(5 min) would yield 14:35, since it's closer to that than 14:30.

Ceil will always round a value up to the nearest timeframe. Example: 14:34.Ceil(5 min) would yield 14:35.

I've personally found floor to be the most useful. In an application I worked on, I needed to group database entries by their created date trimmed to a variable timeframe. Basically, it's a chart that you can expand to cover more and more of a time frame, and the further out you go, the wider the groups should get. At minimum resolution, everything is floored to the nearest minute. At max resolution, everything is floored to the nearest hour, with 5, 15, and 30 minute groupings in between.

Again, credit where credit is due: I didn't write these myself. I found the algorithms on the linked SO thread and made extension methods out of them.

Hope you find them useful!

1 Comments On This Entry

Page 1 of 1

Sergio Tapia 

24 February 2011 - 07:54 PM
Definitely stealing these for my Snippets.
0
Page 1 of 1

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

Recent Entries

Recent Comments

3 user(s) viewing

3 Guests
0 member(s)
0 anonymous member(s)