Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping DateTime by arbitrary time intervals

Tags:

c#

linq

Hi I'm attempting to group a collection of objects by their DateTime property and I am having a strange issue. Currently I have the following:

TimeSpan interval = TimeSpan.FromMinutes(45);
var selected = from date in item.Dates
               group date by (date.Ticks / interval.Ticks) into g
               select g;

this basically works, but if the time of the first item is 11:45 then the first group is only 15 mins long. Followed by the next group starting at 12:00 and from there grouping correctly. Am I missing something really simple, or do I need to change the way I attempt to group? What I'm really trying to do is group all my objects into 45 minute chunks.

like image 421
ThomasG Avatar asked Feb 06 '26 16:02

ThomasG


1 Answers

You just need to offset all of the dates before grouping.

TimeSpan offset = startTime.TimeOfDay;
TimeSpan interval = TimeSpan.FromMinutes(45);
var selected = from date in item.Dates
           group date by ((date.Ticks - offset.Ticks) / interval.Ticks) into g
           select g;
like image 151
Nick Larsen Avatar answered Feb 09 '26 06:02

Nick Larsen