惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

H
Hackread – Cybersecurity News, Data Breaches, AI and More
U
Unit 42
Vercel News
Vercel News
Martin Fowler
Martin Fowler
云风的 BLOG
云风的 BLOG
爱范儿
爱范儿
MongoDB | Blog
MongoDB | Blog
J
Java Code Geeks
F
Fortinet All Blogs
MyScale Blog
MyScale Blog
C
Check Point Blog
N
Netflix TechBlog - Medium
Microsoft Azure Blog
Microsoft Azure Blog
aimingoo的专栏
aimingoo的专栏
博客园_首页
WordPress大学
WordPress大学
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
IT之家
IT之家
Last Week in AI
Last Week in AI
罗磊的独立博客
大猫的无限游戏
大猫的无限游戏
Jina AI
Jina AI
V
Visual Studio Blog
小众软件
小众软件

博客园 - 空明流光

c# 正则替换与代码动态替换 正则断言备忘 c# await 异步编程工具类 windows 上 使用 conda 以 指定环境 启动 自定义程序 WPF 数据绑定通过 ElementName 失效后改为 Reference 正常 与跨域 iframe 通信示例 svn 忽略选项还原 android 应用分身无限多开,开源免费应用 使用 chrome 调试 android webview 前端 dom script C# 文件同步写入锁定 sql server 折腾时不小心去掉了 sysadmin 权限 wpf 中显示约束只创建一个窗口实例 sqlcipher/sqlite 加解密 Xamarin Android 动态修改菜单颜色 XABLD7000: Xamarin.Tools.Zip.ZipException: Renaming temporary file failed: Permission denied .net8 项目指定包还原位置和读取位置以便备份依赖项 wpf 访问内置资源 C# UTF-8 各种编码比较 vs2022 wpf 无法识别 xaml 中定义的控件名称 wpf 使用 cursor 命令 wpf datagrid 过滤数据两种方式?
c# 获取当前时间
空明流光 · 2025-11-16 · via 博客园 - 空明流光
void Main()
{
    var time = GetNetworkTime();
    time.Dump();
}

public static DateTime GetNetworkTime(string ntpServer = "cn.pool.ntp.org")
{
    try
    {
        // NTP消息结构(48字节)
        byte[] ntpData = new byte[48];
        ntpData[0] = 0x1B; // 设置协议版本和模式

        // 创建UDP客户端
        using (var socket = new UdpClient(ntpServer, 123))
        {
            socket.Send(ntpData, ntpData.Length);
            IPEndPoint remoteEP = null;
            ntpData = socket.Receive(ref remoteEP);
        }

        // 解析NTP时间戳(从第40字节开始)
        ulong intPart = (ulong)ntpData[40] << 24 | (ulong)ntpData[41] << 16 |
                       (ulong)ntpData[42] << 8 | ntpData[43];
        ulong fractPart = (ulong)ntpData[44] << 24 | (ulong)ntpData[45] << 16 |
                         (ulong)ntpData[46] << 8 | ntpData[47];

        // 转换为UNIX时间戳(1900年1月1日 → 1970年1月1日)
        ulong milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
        var networkTime = new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)
            .AddMilliseconds(milliseconds);

        return networkTime.ToLocalTime();
    }
    catch (Exception ex)
    {
        Console.WriteLine($"获取网络时间失败: {ex.Message}");
        return DateTime.Now; // 失败时返回本地时间
    }
}

桂棹兮兰桨,击空明兮溯流光。

posted on 2025-11-16 18:36  空明流光  阅读(31)  评论()    收藏  举报