static double ToTimestamp(this DateTime dt, UnixTimestampType unixTimestampType) { var timeDiff = new TimeSpan(dt.ToUniversalTime().Ticks - Constants.UnixEpochTicks); var total = unixTimestampType switch { UnixTimestampType.Milliseconds => timeDiff.TotalMilliseconds, UnixTimestampType.Seconds => timeDiff.TotalSeconds, _ => throw new ArgumentOutOfRangeException(nameof(unixTimestampType), unixTimestampType, null), }; return((double)Math.Floor(total)); }
static long GetTicks(long timestamp, UnixTimestampType unixTimestampType) { long ticks; switch (unixTimestampType) { case UnixTimestampType.Milliseconds: if (timestamp > Constants.TimestampMillisecondsMaxValue) { timestamp = Constants.TimestampMillisecondsMaxValue; } ticks = Constants.UnixEpochTicks + TimeSpan.FromMilliseconds(timestamp).Ticks; break; case UnixTimestampType.Seconds: ticks = Constants.UnixEpochTicks + TimeSpan.FromSeconds(timestamp).Ticks; break; default: throw new ArgumentOutOfRangeException(nameof(unixTimestampType), unixTimestampType, null); } return(ticks); }
/// <summary> /// 将 Unix时间戳根据 <see cref="UnixTimestampType"/> 转换为 <see cref="DateTimeOffset"/> /// </summary> /// <param name="timestamp"></param> /// <param name="type"></param> /// <param name="convertLocalTime"></param> /// <returns></returns> public static DateTimeOffset ToDateTimeOffset(this long timestamp, UnixTimestampType type = UnixTimestampType.Milliseconds, bool convertLocalTime = true) { var ticks = GetTicks(timestamp, type); return(GetDateTimeOffset(ticks, convertLocalTime)); }