Reputation: 4556
What's the best way to trim a DateTime object to a specific precision? For instance, if I have a DateTime with a value of '2008-09-29 09:41:43', but I only want it's precision to be to the minute, is there any better way to do it than this?
private static DateTime TrimDateToMinute(DateTime date)
{
return new DateTime(
date.Year,
date.Month,
date.Day,
date.Hour,
date.Minute,
0);
}
What I would really want is to make it variable so that I could set its precision to the second, minute, hour, or day.
Upvotes: 71
Views: 40701
Reputation: 4170
I like this method. Someone mentioned it was good to preserve the Date Kind, etc. This accomplishes that because you dont have to make a new DateTime. The DateTime is properly cloned from the original DateTime and it simply subtracts the remainder ticks.
public static DateTime FloorTime(DateTime dt, TimeSpan interval)
{
return dt.AddTicks(-1 * (dt.Ticks % interval.Ticks));
}
usage:
dt = FloorTime(dt, TimeSpan.FromMinutes(5)); // floor to the nearest 5min interval
dt = FloorTime(dt, TimeSpan.FromSeconds(1)); // floor to the nearest second
dt = FloorTime(dt, TimeSpan.FromDays(1)); // floor to the nearest day
Upvotes: 8
Reputation: 3014
static class Program
{
//using extension method:
static DateTime Trim(this DateTime date, long roundTicks)
{
return new DateTime(date.Ticks - date.Ticks % roundTicks, date.Kind);
}
//sample usage:
static void Main(string[] args)
{
Console.WriteLine(DateTime.Now);
Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerDay));
Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerHour));
Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerMillisecond));
Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerMinute));
Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerSecond));
Console.ReadLine();
}
}
Upvotes: 126
Reputation: 742
There are some good solutions presented here, but when I need to do this, I simply do:
DateTime truncDate;
truncDate = date.Date; // trim to day
truncDate = date.Date + TimeSpan.Parse(string.Format("{0:HH:00:00}", date)); // trim to hour
truncDate = date.Date + TimeSpan.Parse(string.Format("{0:HH:mm}", date)); // trim to minute
truncDate = date.Date + TimeSpan.Parse(string.Format("{0:HH:mm:ss}", date)); // trim to second
Hope it helps.
Upvotes: 1
Reputation: 4574
You could use an enumeration
public enum DateTimePrecision
{
Hour, Minute, Second
}
public static DateTime TrimDate(DateTime date, DateTimePrecision precision)
{
switch (precision)
{
case DateTimePrecision.Hour:
return new DateTime(date.Year, date.Month, date.Day, date.Hour, 0, 0);
case DateTimePrecision.Minute:
return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, 0);
case DateTimePrecision.Second:
return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second);
default:
break;
}
}
and expand as required.
Upvotes: 9
Reputation: 428
DateTime dt = new DateTime()
dt = dt.AddSeconds(-dt.Second)
Above code will trim seconds.
Upvotes: -2