| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace MvvmScaffoldFrame48.DLL.SystemTools
- {
- public static class TimeStampTools
- {
- public static DateTime FromUnixTimestamp(long timestamp, bool isMilliseconds = false)
- {
- try
- {
- // 如果未指定单位,尝试自动检测
- if (!isMilliseconds)
- {
- // 如果时间戳看起来像毫秒级(13位数字)
- if (timestamp.ToString().Length > 10)
- {
- isMilliseconds = true;
- }
- }
- if (isMilliseconds)
- {
- // 验证毫秒级时间戳范围
- const long minMilliTimestamp = -62135596800000; // 0001-01-01 00:00:00 UTC
- const long maxMilliTimestamp = 253402300799999; // 9999-12-31 23:59:59 UTC
- if (timestamp < minMilliTimestamp || timestamp > maxMilliTimestamp)
- {
- throw new ArgumentOutOfRangeException(nameof(timestamp),
- "毫秒级时间戳超出有效范围");
- }
- DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(timestamp);
- return TimeZoneInfo.ConvertTimeFromUtc(origin, TimeZoneInfo.Local);
- }
- else
- {
- // 验证秒级时间戳范围
- const long minTimestamp = -62135596800;
- const long maxTimestamp = 253402300799;
- if (timestamp < minTimestamp || timestamp > maxTimestamp)
- {
- throw new ArgumentOutOfRangeException(nameof(timestamp),
- "秒级时间戳超出有效范围");
- }
- DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(timestamp);
- return TimeZoneInfo.ConvertTimeFromUtc(origin, TimeZoneInfo.Local);
- }
- }
- catch (ArgumentOutOfRangeException)
- {
- throw;
- }
- catch (Exception ex)
- {
- throw new ArgumentException($"无法转换时间戳 {timestamp}: {ex.Message}", ex);
- }
- }
- }
- }
|