MartinaRaf
MartinaRaf

Reputation: 77

c# linq group by a datetime to the nearest second

I would like to group the following datetimes together using Linq in c# as follows:

Group 1:

2015-03-03 15:18:42.880
2015-03-03 15:18:42.897

Group 2:

2015-03-19 16:29:59.977
2015-03-19 16:29:59.983
2015-03-19 16:29:59.983

Group 3:

2015-03-26 11:27:29.813
2015-03-26 11:27:30.030
2015-03-26 11:27:30.030

Group 4:

2015-03-27 15:13:58.483
2015-03-27 15:13:58.483
2015-03-27 15:13:58.500

I'm having an issue with some of these groupings. Currently I'm just grouping the dates ignoring the milliseconds portion. What I would like to do it group dates which are within 1 second of each other without the milliseconds. This is my query so far:

var query =
from trans in TransactionTable.AsEnumerable()                                                        
let dateWithoutMilliseconds = trans.Field<DateTime>("TranactionDate").AddMilliseconds(-trans.Field<DateTime>("TranactionDate").Millisecond)
group trans by dateWithoutMilliseconds into g
select new
{                                   
TransDate = g.Key,                                                                
};

Upvotes: 2

Views: 1100

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186708

You can convert to Ticks (100 nano seconds), round up, and then back to DateTime. In case you want just to GroupBy just round up Ticks:

DateTime source = ...
...
// Up to nearest second
const int shift = 10000000;

DateTime result = new DateTime(
  (source.Ticks / shift + (source.Ticks % shift >= (shift / 2) ? 1 : 0)) * shift);

// If you want just a key to group by
long key = (source.Ticks / shift + (source.Ticks % shift >= (shift / 2) ? 1 : 0)) * shift;

Upvotes: 1

Related Questions