假设我有一个DateTime:
DateTime datetime(2013,11,08,17,45,23,300);//2013:11:08 17:45:23:300
我想按不同的准确度截断这个DateTime,并返回最小的DateTime,如下所示:
Year: 2013:01:01 00:00:00:000
Quarter: 2013:10:01 00:00:00:000 //Oct is first month of that quarter
Month: 2013:11:01 00:00:00:000
Week: 2013:11:03 00:00:00:000 // 3rd is Sunday of that week
Day: 2013:11:08 00:00:00:000
Hours 2013:11:08 17:00:00:000
Minute: 2013:11:08 17:45:00:000
Second: 2013:11:08 17:45:23:000
我知道你可以通过改变DateTime的不同部分来做到这一点,有没有更好的方法呢?或者我已经知道.net中有功能的构建吗?
答案 0 :(得分:4)
我所知道的并不存在,但这应该可以解决问题:
public enum Accuracy { Year, Quarter, Month, Week, Day, Hour, Minute, Second};
private static DateTime TruncateDate(DateTime inDate, Accuracy accuracy){
switch (accuracy)
{
case Accuracy.Year:
return new DateTime(inDate.Year, 1, 1);
case Accuracy.Quarter:
int i = inDate.Month % 3;
return new DateTime(inDate.Year, inDate.Month - i + 1, 1);
case Accuracy.Month:
return new DateTime(inDate.Year, inDate.Month, 1);
case Accuracy.Week:
return new DateTime(inDate.Year, inDate.Month, inDate.Day).AddDays(-(int)inDate.DayOfWeek);
case Accuracy.Day:
return new DateTime(inDate.Year, inDate.Month, inDate.Day);
case Accuracy.Hour:
return new DateTime(inDate.Year, inDate.Month, inDate.Day, inDate.Hour, 0, 0);
case Accuracy.Minute:
return new DateTime(inDate.Year, inDate.Month, inDate.Day, inDate.Hour, inDate.Minute, 0);
case Accuracy.Second:
return new DateTime(inDate.Year, inDate.Month, inDate.Day, inDate.Hour, inDate.Minute, inDate.Second);
default:
throw new ArgumentOutOfRangeException("accuracy");
}
}
修改:在周日不同月份时更正。
答案 1 :(得分:1)
根据我自己的评论:
public static DateTime Truncate(this DateTime dt, TimeSpan resolution)
{
return new DateTime(dt.Ticks - dt.Ticks % resolution.Ticks);
}
修改强>
使用示例:var truncated = dt.Truncate(Timespan.FromHours(1.0));
正如我在该评论中所说的那样,对于长度(数学上)因实例而异的年份和季度的事情,这没有用。
答案 2 :(得分:0)
这会在今天午夜创建一个DateTime。您可以使用任何DateTime并调用'Date'属性来摆脱小时/分钟/秒。
// 1/7/2014 12:00:00 AM
DateTime.Now.Date
从那里得到像上午5点这样的具体时间
var 5amDate = DateTime.Now.Date.AddHours(5)
// 1/7/2014 5:00:00 AM