将DateTime对象修剪为特定精度的最佳方法是什么?例如,如果我的DateTime值为'2008-09-29 09:41:43',但我只想要精确到分钟,有没有更好的方法来做到这一点?
private static DateTime TrimDateToMinute(DateTime date) { return new DateTime( date.Year, date.Month, date.Day, date.Hour, date.Minute, 0); }
我真正想要的是让它变量,以便我可以将其精度设置为秒,分钟,小时或日.
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(); } }
您可以使用枚举
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; } }
并根据需要进行扩展.