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

如何在Blazor中全局注入th-TH CultureInfo实现DateTime泰国格式输出

实现方案

以下两种方案都可以满足需求,可根据你的项目场景选择:


方案1:全局配置默认文化(最简便,无需额外注入)

这个方案配置后全局所有线程默认使用泰国文化,直接调用DateTime.Now.ToString("dd-MM-yyyy")就能自动输出佛历格式的日期,比如02-11-2564。

.NET 6+ 版本(Program.cs配置)

在Program.cs文件的var builder = WebApplication.CreateBuilder(args);代码之后添加如下配置:

using System.Globalization;

// 全局设置默认文化为泰国文化
var thCulture = new CultureInfo("th-TH");
CultureInfo.DefaultThreadCurrentCulture = thCulture;
CultureInfo.DefaultThreadCurrentUICulture = thCulture;

旧版本(Startup.cs配置)

直接在ConfigureServices方法中添加上面的文化配置代码即可。


方案2:将泰国文化作为服务注入使用

如果你后续有动态切换文化的需求,或者需要在自定义服务中调用泰国文化实例,可以按如下方式注册:

单例模式注册(全局唯一实例,适合固定文化的场景)

// Program.cs中添加
builder.Services.AddSingleton(new CultureInfo("th-TH"));

作用域模式注册(适合每个用户/请求单独配置文化的场景)

// Program.cs中添加
builder.Services.AddScoped(_ => new CultureInfo("th-TH"));

注入使用示例

  • Razor页面调用:
@inject CultureInfo ThCulture

<p>泰国格式日期:@DateTime.Now.ToString("dd-MM-yyyy", ThCulture)</p>
  • 后端服务调用:
public class YourCustomService
{
    private readonly CultureInfo _thCulture;
    // 构造函数注入
    public YourCustomService(CultureInfo thCulture)
    {
        _thCulture = thCulture;
    }

    public string GetCurrentThaiDate()
    {
        return DateTime.Now.ToString("dd-MM-yyyy", _thCulture);
    }
}

Blazor WebAssembly 注意事项

WASM项目的配置逻辑和上面完全一致,直接在WASM项目的Program.cs中配置默认文化或者注册服务即可,不需要额外的服务端适配。

内容的提问来源于stack exchange,提问作者รัฐพล.James

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 14:54:02