using System;
public enum TimeUnit : byte {
Unknown = 0x00,
Nanosecond = 0x01,
Millisecond = 0x02,
Second = 0x04,
Minute = 0x08,
Hour = 0x10,
Day = 0x20,
Month = 0x40,
Year = 0x80,
AllDate = TimeUnit.Year | TimeUnit.Month | TimeUnit.Day,
AllTime = TimeUnit.Hour | TimeUnit.Minute | TimeUnit.Second,
UpToNanosecond = TimeUnit.Nanosecond | TimeUnit.Millisecond | TimeUnit.Second | TimeUnit.Minute | TimeUnit.Hour | TimeUnit.Day | TimeUnit.Month | TimeUnit.Year,
UpToMillisecond = TimeUnit.Millisecond | TimeUnit.Second | TimeUnit.Minute | TimeUnit.Hour | TimeUnit.Day | TimeUnit.Month | TimeUnit.Year,
UpToSecond = TimeUnit.Second | TimeUnit.Minute | TimeUnit.Hour | TimeUnit.Day | TimeUnit.Month | TimeUnit.Year,
UpToMinute = TimeUnit.Minute | TimeUnit.Hour | TimeUnit.Day | TimeUnit.Month | TimeUnit.Year,
UpToHour = TimeUnit.Hour | TimeUnit.Day | TimeUnit.Month | TimeUnit.Year,
UpToDay = TimeUnit.Day | TimeUnit.Month | TimeUnit.Year,
UpToMonth = TimeUnit.Month | TimeUnit.Year,
};
public static partial class DateTimeEx {
private static void _Compare( ref int result, int flags, TimeUnit tu, int a, int b ) {
var which = (int) tu;
if ( 0 != ( flags & which ) ) {
if ( a != b ) result |= which;
}
}
public static TimeUnit Compare( this DateTime a, DateTime b, TimeUnit unit ) {
int result = 0;
var flags = (int) unit;
_Compare( ref result, flags, TimeUnit.Millisecond, a.Millisecond, b.Millisecond );
_Compare( ref result, flags, TimeUnit.Second, a.Second, b.Second );
_Compare( ref result, flags, TimeUnit.Minute, a.Minute, b.Minute );
_Compare( ref result, flags, TimeUnit.Hour, a.Hour, b.Hour );
_Compare( ref result, flags, TimeUnit.Day, a.Day, b.Day );
_Compare( ref result, flags, TimeUnit.Month, a.Month, b.Month );
_Compare( ref result, flags, TimeUnit.Year, a.Year, b.Year );
return (TimeUnit) result;
}
}
public static class Tests {
private static void TestCompare() {
var test = DateTime.UtcNow;
var ts = test.ToUnixTimestamp( true );
var test2 = DateTimeEx.ToDateTime( ts, true );
var ok = 0 == DateTimeEx.Compare( test, test2, TimeUnit.UpToSecond );
Log.Assert( ok );
ts = test.ToUnixTimestamp( false );
test2 = DateTimeEx.ToDateTime( ts, false );
ok = 0 == DateTimeEx.Compare( test, test2, TimeUnit.UpToSecond );
Log.Assert( ok );
}
}