有没有更好的方法来修剪date时间到一个特定的精度?
将DateTime对象修剪为特定精度的最佳方法是什么? 例如,如果我有一个值为'2008-09-29 09:41:43'的DateTime,但是我只希望精确到一分钟,有没有比这更好的方法来做到这一点?
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); } //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; } }
并根据需要进行扩展。
这里提出了一些很好的解决scheme,但是当我需要这样做时,我只需要:
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
希望能帮助到你。
static DateTime TrimDate(DateTime date, long roundTicks) { return new DateTime(date.Ticks - date.Ticks % roundTicks); } //sample usage: static void Main(string[] args) { Console.WriteLine(DateTime.Now); Console.WriteLine(TrimDate(DateTime.Now, TimeSpan.TicksPerDay)); Console.WriteLine(TrimDate(DateTime.Now, TimeSpan.TicksPerHour)); Console.WriteLine(TrimDate(DateTime.Now, TimeSpan.TicksPerMillisecond)); Console.WriteLine(TrimDate(DateTime.Now, TimeSpan.TicksPerMinute)); Console.WriteLine(TrimDate(DateTime.Now, TimeSpan.TicksPerSecond)); Console.ReadLine(); }
我喜欢这种方法。 有人提到保存datetypes是很好的,等等。这样做的结果是,因为它没有创build一个新的date,它只是减去余数。
private DateTime FloorToHour(DateTime dt) { return dt.AddTicks(-1 * (dt.Ticks % TimeSpan.TicksPerHour)); }
DateTime dt = new DateTime() dt = dt.AddSeconds(-dt.Second)
上面的代码将修剪秒。
如果您的时间和date与( time_t )类似(连续),您可以简单地使用模数来获得完整的分钟数(%60),小时数等等。
根据我的经验,这些值似乎与实际时间一致(模数60发生在整分钟),但是这在任何地方都是不能保证的。
这里是代码来获得你想要的(亚秒分辨率):
/* * Returns millisecond timing (in seconds) for the current time. * * Note: This function should be called once in single-threaded mode in Win32, * to get it initialized. */ double now_secs(void) { #if (defined PLATFORM_WIN32) || (defined PLATFORM_POCKETPC) /* * Windows FILETIME values are "100-nanosecond intervals since * January 1, 1601 (UTC)" (MSDN). Well, we'd want Unix Epoch as * the offset and it seems, so would they: * * <http://msdn.microsoft.com/en-us/library/ms724928(VS.85).aspx> */ SYSTEMTIME st; FILETIME ft; ULARGE_INTEGER uli; static ULARGE_INTEGER uli_epoch; // Jan 1st 1970 0:0:0 if (uli_epoch.HighPart==0) { st.wYear= 1970; st.wMonth= 1; // Jan st.wDay= 1; st.wHour= st.wMinute= st.wSecond= st.wMilliseconds= 0; // st.wDayOfWeek= 0; // ignored if (!SystemTimeToFileTime( &st, &ft )) FAIL( "SystemTimeToFileTime", GetLastError() ); uli_epoch.LowPart= ft.dwLowDateTime; uli_epoch.HighPart= ft.dwHighDateTime; } GetSystemTime( &st ); // current system date/time in UTC if (!SystemTimeToFileTime( &st, &ft )) FAIL( "SystemTimeToFileTime", GetLastError() ); uli.LowPart= ft.dwLowDateTime; uli.HighPart= ft.dwHighDateTime; /* 'double' has less accuracy than 64-bit int, but if it were to degrade, * it would do so gracefully. In practise, the integer accuracy is not * of the 100ns class but just 1ms (Windows XP). */ return (double)(uli.QuadPart - uli_epoch.QuadPart) / 10000000.0; #else struct timeval tv; // { // time_t tv_sec; /* seconds since Jan. 1, 1970 */ // suseconds_t tv_usec; /* and microseconds */ // }; int rc= gettimeofday( &tv, NULL /*time zone not used any more (in Linux)*/ ); assert( rc==0 ); return ((double)tv.tv_sec) + ((tv.tv_usec)/1000) / 1000.0; #endif }