当前我正在使用此:
new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day,
DateTime.Now.Hour, DateTime.Now.Minute, 0)
还有其他方法可以将秒和毫秒直接设置为0。
您当前的代码很危险,因为您要多次评估DateTime.Now
。最好是:
// Do you *definitely* want the current date/time in the system local time zone?
// Might be correct for local client apps; almost certainly not for server-side code.
DateTime now = DateTime.Now;
DateTime rounded = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0);
还不错。另一种选择是:
DateTime now = DateTime.Now;
DateTime rounded = now.Date + new TimeSpan(now.Hour, now.Minute, 0);
如果您绝对要使用DateTime
,并且您绝对要使用系统本地时区,那可能就是我要做的。
作为我的Noda Time项目的插件,类似于:
rounded = now.With(TimeAdjusters.TruncateToMinute);
...但是根据您想让now
排在首位的类型,您还有很多选择要考虑。