之前工作中经常用到日期和时间戳互转的方法,弄成了扩展方法,方便调用,在这里记录一下

public static class DateTimeExtentions
{
    public static DateTime ToDateTime(this long timestamp)
    {
        var dateTimeOffset = timestamp.IsUnixTimeMilliseconds()
            ? DateTimeOffset.FromUnixTimeMilliseconds(timestamp)
            : timestamp.IsUnixTimeSeconds()
                ? DateTimeOffset.FromUnixTimeSeconds(timestamp)
                : throw new ArgumentException("Timestamp not in range.", nameof(timestamp));
        return dateTimeOffset.DateTime.AddHours(DateTimeUtil.TimeZone);
    }

    public static string ToDateTimeString(this long timestamp)
    {
        return timestamp == default ? string.Empty : timestamp.ToDateTime().ToString(DateTimeUtil.FORMAT);
    }

    public static long ToUtcTimestamp(this DateTime dateTime, bool toMilliseconds = false)
    {
        DateTimeOffset dateTimeOffset = new(dateTime);
        return toMilliseconds
            ? dateTimeOffset.ToUnixTimeMilliseconds()
            : dateTimeOffset.ToUnixTimeSeconds();
    }

    public static long ToUtcTimestamp(this DateTime? dateTime, bool toMilliseconds = false)
    {
        return dateTime.HasValue ? dateTime.Value.ToUtcTimestamp(toMilliseconds) : 0L;
    }

    public static bool IsUnixTimeSeconds(this long timestamp)
        => timestamp is >= (-62135596800L) and <= 253402300799L;

    public static bool IsUnixTimeMilliseconds(this long timestamp)
        => timestamp is > (253402300799L) and >= (-62135596800000L) and <= 253402300799999L;
}