Files
Shrlalgo.RvKits/ShrlAlgoStudio/TimeHelper.cs
2026-02-17 22:17:23 +08:00

49 lines
1.7 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Globalization;
using System.IO;
using System.Net;
namespace ShrlAlgoStudio
{
internal static class TimeHelper
{
public static DateTime GetTrustedTime()
{
// 1. 尝试网络时间 (3秒超时)
try
{
var request = WebRequest.Create("http://www.baidu.com"); // 或 microsoft.com
request.Method = "HEAD";
request.Timeout = 3000;
using (var response = request.GetResponse())
{
string dateStr = response.Headers["Date"];
if (DateTime.TryParseExact(dateStr, "ddd, dd MMM yyyy HH:mm:ss 'GMT'",
CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out DateTime netTime))
return netTime.ToLocalTime();
}
}
catch { }
// 2. 尝试文件系统痕迹校验 (防断网改时间)
DateTime localNow = DateTime.Now;
try
{
// 获取系统目录和临时目录的最后修改时间
DateTime t1 = new DirectoryInfo(Environment.SystemDirectory).LastWriteTime;
DateTime t2 = new DirectoryInfo(Path.GetTempPath()).LastWriteTime;
DateTime latestFileTime = t1 > t2 ? t1 : t2;
// 如果本地时间比系统文件时间还要早超过24小时判定为作弊
if (localNow < latestFileTime.AddHours(-24))
{
return latestFileTime; // 强制使用文件时间
}
}
catch { }
// 3. 兜底
return localNow;
}
}
}