如何在Blazor WASM应用中获取客户端本地时间
Blazor WASM 获取客户端本地时间解决方案
问题根源:Blazor WASM 的 .NET 运行时运行在浏览器沙箱中,无法直接读取客户端系统的时区信息,默认使用 UTC 时间,所以直接调用 DateTime.Now 或 DateTime.Now.ToLocalTime() 无法得到客户端的实际本地时间,必须借助 JavaScript 互操作获取浏览器提供的本地时间。
下面是两种可行的实现方式:
方式一:通过JS返回时间字段构造本地DateTime
- 在
wwwroot/index.html的<script>标签中添加以下JS方法:
window.getLocalDateTimeDetails = () => { const now = new Date(); return { year: now.getFullYear(), month: now.getMonth() + 1, // JavaScript中月份从0开始,需加1转为标准月份 day: now.getDate(), hour: now.getHours(), minute: now.getMinutes(), second: now.getSeconds(), millisecond: now.getMilliseconds() }; };
- 在Blazor组件中注入
IJSRuntime并调用该方法,构造本地时间:
@inject IJSRuntime JSRuntime <div>客户端本地时间:@localTime?.ToString("yyyy-MM-dd HH:mm:ss.fff")</div> @code { private DateTime? localTime; protected override async Task OnInitializedAsync() { var timeData = await JSRuntime.InvokeAsync<LocalTimeInfo>("getLocalDateTimeDetails"); localTime = new DateTime( timeData.Year, timeData.Month, timeData.Day, timeData.Hour, timeData.Minute, timeData.Second, timeData.Millisecond, DateTimeKind.Local); } // 用于接收JS返回的时间数据的模型类 private class LocalTimeInfo { public int Year { get; set; } public int Month { get; set; } public int Day { get; set; } public int Hour { get; set; } public int Minute { get; set; } public int Second { get; set; } public int Millisecond { get; set; } } }
方式二:通过JS返回ISO字符串解析本地时间
- 在
wwwroot/index.html中添加简化的JS方法:
window.getLocalDateTimeISO = () => { return new Date().toISOString(); };
- 在Blazor组件中调用并解析:
@inject IJSRuntime JSRuntime <div>客户端本地时间:@localTime?.ToString("yyyy-MM-dd HH:mm:ss")</div> @code { private DateTime? localTime; protected override async Task OnInitializedAsync() { var isoStr = await JSRuntime.InvokeAsync<string>("getLocalDateTimeISO"); // 解析UTC格式的ISO字符串,再转换为本地时间 localTime = DateTime.Parse(isoStr).ToLocalTime(); } }
两种方式都能准确获取到客户端任务栏显示的本地时间,方式一的精度更高,方式二更简洁。
内容的提问来源于stack exchange,提问作者Cincy Steve
相关产品推荐
相关产品推荐

