You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor中如何向IJSRuntime.InvokeVoidAsync传递日期对象?

Blazor传递DateTime到JavaScript的可靠方案

直接传递C# DateTime 对象到JavaScript时,会被默认序列化为依赖服务器区域设置的字符串,这种方式存在解析风险——不同浏览器或区域环境可能无法正确识别格式,导致new Date()转换失败或得到错误的时间。下面是两种更可靠的传递方式:

1. 传递Unix时间戳(毫秒级)

时间戳是数字类型,不存在格式歧义,是最可靠的传递方式:

C# 端修改

将DateTime转换为Unix毫秒时间戳:

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        var parameters = new
        {
            timestamp = new DateTimeOffset(DateValue).ToUnixTimeMilliseconds()
        };
        await JSRuntime.InvokeVoidAsync("window.myfunction", _inputReference, parameters);      
    }
}

JavaScript 端处理

直接用时间戳初始化Date对象:

window.myfunction = (options) => {
    const date = new Date(options.timestamp);
    console.log(date); // 得到正确的Date实例
};

2. 传递ISO 8601标准格式字符串

ISO 8601是跨平台的时间格式标准,所有现代浏览器都能正确解析:

C# 端修改

主动将DateTime序列化为ISO 8601格式(使用"o"格式符,即Round-trip格式):

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        var parameters = new
        {
            isoDate = DateValue.ToString("o")
        };
        await JSRuntime.InvokeVoidAsync("window.myfunction", _inputReference, parameters);      
    }
}

JavaScript 端处理

用ISO字符串初始化Date对象:

window.myfunction = (options) => {
    const date = new Date(options.isoDate);
    console.log(date); // 可靠解析为Date实例
};

方案对比

  • 时间戳:性能略优,无格式解析成本,但可读性差;
  • ISO 8601字符串:可读性强,便于调试,适合需要查看原始时间值的场景。

两种方式都能彻底避免区域格式差异带来的解析问题,比依赖默认字符串转换的方式可靠得多。

内容的提问来源于stack exchange,提问作者Jeremy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 10:45:37