38 lines
1021 B
C#
38 lines
1021 B
C#
namespace InnovEnergy.Lib.Utils;
|
|
|
|
public static class DateTimeUtils
|
|
{
|
|
public static DateTime Epoch { get; } = new DateTime
|
|
(
|
|
year: 1970,
|
|
month: 1,
|
|
day: 1,
|
|
hour: 0,
|
|
minute: 0,
|
|
second: 0,
|
|
DateTimeKind.Utc
|
|
);
|
|
|
|
public static Int64 ToUnixTime(this DateTime dateTime)
|
|
{
|
|
var timeSinceEpoch = dateTime.ToUniversalTime() - Epoch;
|
|
return timeSinceEpoch.Ticks / TimeSpan.TicksPerSecond;
|
|
}
|
|
|
|
public static DateTime DateTimeFromUnixTime(this IConvertible unixTime)
|
|
{
|
|
var epochTicks = Epoch.Ticks + unixTime.ConvertTo<Double>() * TimeSpan.TicksPerSecond;
|
|
|
|
return new DateTime(epochTicks.ConvertTo<Int64>(), DateTimeKind.Utc);
|
|
}
|
|
|
|
public static DateTime Round(this DateTime date, TimeSpan interval)
|
|
{
|
|
var i = interval.Ticks;
|
|
var t = date.Ticks;
|
|
|
|
var intervalTicks = (t + i / 2 + 1) / i * i;
|
|
|
|
return new DateTime(intervalTicks, date.Kind);
|
|
}
|
|
} |