using System; using PCL.Core.App.Localization; using System.Globalization; namespace PCL.Core.Utils; /// /// 提供与时间相关的实用方法。 /// public static class TimeUtils { /// /// 获取格式类似于“11:08:52.037”的当前时间字符串。 /// /// 格式化后的时间字符串。 public static string GetTimeNow() { return DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture); } /// /// 获取系统运行时间(毫秒),保证为正长整型,且大于 1。 /// /// /// 此方法基于 Environment.TickCount,但在 .NET 框架中,我们有更可靠的替代方案。 /// /// 系统运行毫秒数。 public static long GetTimeTick() { // 原始代码处理了 Environment.TickCount 的符号溢出问题(在 24.8 天后), // 但在现代 .NET 中,我们有更可靠、更精确的 Stopwatch 类。 // 为了保持原函数意图,这里直接返回 Environment.TickCount。 // 注意:Environment.TickCount 在64位系统中可能为负,不推荐在重要场景使用。 return Environment.TickCount64; } /// /// 获取十进制 Unix 时间戳(秒)。 /// /// 当前时间的 Unix 时间戳。 public static long GetUnixTimestamp() { return DateTimeOffset.UtcNow.ToUnixTimeSeconds(); } /// /// 将 Unix 时间戳(秒)转换为本地时区的日期时间。 /// /// Unix 时间戳(秒),表示自 1970-01-01 00:00:00 UTC 起的秒数。 /// 转换后的本地日期时间。 /// 为负数或过大时抛出。 public static DateTimeOffset FromUnixTimestamp(long unixTimestamp) { if (unixTimestamp < 0) throw new ArgumentOutOfRangeException(nameof(unixTimestamp), "Unix 时间戳不能为负数。"); try { return DateTimeOffset.FromUnixTimeSeconds(unixTimestamp).ToLocalTime(); } catch (ArgumentOutOfRangeException ex) { throw new ArgumentOutOfRangeException(nameof(unixTimestamp), "Unix 时间戳超出有效范围。", ex.Message); } } /// /// 将 UTC 时间转换为当前时区的时间。 /// /// UTC 日期时间。 /// 转换后的本地日期时间。 public static DateTimeOffset ToLocalTime(DateTimeOffset utcDate) { return utcDate.ToLocalTime(); } /// /// 将 Unix 时间戳(秒)转换为当前展示区域性格式的本地时间字符串。 /// /// Unix 时间戳(秒),表示自 1970-01-01 00:00:00 UTC 起的秒数。 /// 使用当前展示区域性格式化后的本地时间字符串。 /// 为负数或过大时抛出。 public static string FormatUnixTimestamp(long unixTimestamp) { return Lang.Date(FromUnixTimestamp(unixTimestamp), "g"); } }