TimeStampTools.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace MvvmScaffoldFrame48.DLL.SystemTools
  7. {
  8. public static class TimeStampTools
  9. {
  10. public static DateTime FromUnixTimestamp(long timestamp, bool isMilliseconds = false)
  11. {
  12. try
  13. {
  14. // 如果未指定单位,尝试自动检测
  15. if (!isMilliseconds)
  16. {
  17. // 如果时间戳看起来像毫秒级(13位数字)
  18. if (timestamp.ToString().Length > 10)
  19. {
  20. isMilliseconds = true;
  21. }
  22. }
  23. if (isMilliseconds)
  24. {
  25. // 验证毫秒级时间戳范围
  26. const long minMilliTimestamp = -62135596800000; // 0001-01-01 00:00:00 UTC
  27. const long maxMilliTimestamp = 253402300799999; // 9999-12-31 23:59:59 UTC
  28. if (timestamp < minMilliTimestamp || timestamp > maxMilliTimestamp)
  29. {
  30. throw new ArgumentOutOfRangeException(nameof(timestamp),
  31. "毫秒级时间戳超出有效范围");
  32. }
  33. DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(timestamp);
  34. return TimeZoneInfo.ConvertTimeFromUtc(origin, TimeZoneInfo.Local);
  35. }
  36. else
  37. {
  38. // 验证秒级时间戳范围
  39. const long minTimestamp = -62135596800;
  40. const long maxTimestamp = 253402300799;
  41. if (timestamp < minTimestamp || timestamp > maxTimestamp)
  42. {
  43. throw new ArgumentOutOfRangeException(nameof(timestamp),
  44. "秒级时间戳超出有效范围");
  45. }
  46. DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(timestamp);
  47. return TimeZoneInfo.ConvertTimeFromUtc(origin, TimeZoneInfo.Local);
  48. }
  49. }
  50. catch (ArgumentOutOfRangeException)
  51. {
  52. throw;
  53. }
  54. catch (Exception ex)
  55. {
  56. throw new ArgumentException($"无法转换时间戳 {timestamp}: {ex.Message}", ex);
  57. }
  58. }
  59. }
  60. }