Si tiene tiempo & fecha como un número (continua) similar a time_t, puede simplemente usar módulo de conseguir minutos completos (60%), hora, y así sucesivamente.
En mi experiencia, los valores parecen estar alineados con el tiempo real (el módulo 60 se produce en el minuto completo), pero es muy probable que esto no esté garantizado en ninguna parte.
Aquí es código para obtener lo que quiere (con menos de un segundo de resolución):
/*
* 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
}
Me gusta mucho y si estaba usando el framework 3.5, esta es la ruta que tomaría, a menos que haya algo mejor todavía. Desafortunadamente, estoy usando 2.0, así que tendré que apegarme a tu primera respuesta. ¡Gracias! –
Si lo está convirtiendo en un método de extensión de propósito general, vale la pena preservar DateTimeKind (Unspecified/Utc/Local): return new DateTime (date.Ticks - date.Ticks% roundTicks, date.Kind); – Joe
... o una línea que también conserva la propiedad Tipo: d = d.AddTicks (- (d.Ticks + 30 * TimeSpan.TicksPerSecond)% TimeSpan.TicksPerMinute); – Joe