Skip to content

Commit f233e64

Browse files
committed
feat(timer): 添加毫秒级时间戳转 TimeSpan 的方法
新增 TimeSpanWithTimestampUtcMs 和 TimeSpanWithTimestampWithTimeZoneMs 方法, 支持将毫秒级 Unix 时间戳转换为 TimeSpan 对象。
1 parent 5d74c4a commit f233e64

2 files changed

Lines changed: 38 additions & 0 deletions

File tree

GameFrameX.Foundation.Utility/Time/TimerHelper.Timestamp.TimeZone.cs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,4 +55,25 @@ public static TimeSpan TimeSpanWithTimestampWithTimeZone(long timestamp)
5555
// 直接将秒数转换为TimeSpan
5656
return TimeSpan.FromSeconds(timestamp);
5757
}
58+
59+
/// <summary>
60+
/// 将给定的毫秒时间戳转换为相对于Epoch的 TimeSpan 对象(基于TimeZone)
61+
/// </summary>
62+
/// <param name="timestampMilliseconds">自1970年1月1日午夜以来经过的毫秒数。</param>
63+
/// <returns>一个 TimeSpan 对象,表示从Epoch到给定毫秒时间戳的间隔。</returns>
64+
/// <exception cref="ArgumentOutOfRangeException">当毫秒时间戳超出有效范围时抛出此异常</exception>
65+
/// <remarks>
66+
/// 此方法将毫秒时间戳转换为TimeSpan对象
67+
/// 使用当前时区 (<see cref="CurrentTimeZone"/>) 的纪元时间作为基准
68+
/// </remarks>
69+
public static TimeSpan TimeSpanWithTimestampWithTimeZoneMs(long timestampMilliseconds)
70+
{
71+
if (timestampMilliseconds < -62135596800000L || timestampMilliseconds > 253402300799999L)
72+
{
73+
throw new ArgumentOutOfRangeException(nameof(timestampMilliseconds), "Timestamp is out of range.");
74+
}
75+
76+
// 直接将毫秒数转换为TimeSpan
77+
return TimeSpan.FromMilliseconds(timestampMilliseconds);
78+
}
5879
}

GameFrameX.Foundation.Utility/Time/TimerHelper.Timestamp.UTC.cs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,4 +54,21 @@ public static TimeSpan TimeSpanWithTimestampUtc(long timestamp)
5454
// 直接将秒数转换为TimeSpan
5555
return TimeSpan.FromSeconds(timestamp);
5656
}
57+
58+
/// <summary>
59+
/// 将给定的毫秒时间戳转换为相对于EpochUtc的 TimeSpan 对象。
60+
/// </summary>
61+
/// <param name="timestampMilliseconds">自1970年1月1日午夜以来经过的毫秒数。</param>
62+
/// <returns>一个 TimeSpan 对象,表示从EpochUtc到给定毫秒时间戳的间隔。</returns>
63+
/// <exception cref="ArgumentOutOfRangeException">当毫秒时间戳超出有效范围时抛出此异常</exception>
64+
public static TimeSpan TimeSpanWithTimestampUtcMs(long timestampMilliseconds)
65+
{
66+
if (timestampMilliseconds < -62135596800000L || timestampMilliseconds > 253402300799999L)
67+
{
68+
throw new ArgumentOutOfRangeException(nameof(timestampMilliseconds), LocalizationService.GetString(LocalizationKeys.Exceptions.TimestampOutOfRange));
69+
}
70+
71+
// 直接将毫秒数转换为TimeSpan
72+
return TimeSpan.FromMilliseconds(timestampMilliseconds);
73+
}
5774
}

0 commit comments

Comments
 (0)