首页 > 解决方案 > 如何设置全局函数来为不同语言环境转换所有不同格式的日期?

问题描述

我们正在创建一个具有不同语言环境的系统。我可以说所有可以在这里找到的 .net 语言环境: https ://dotnetfiddle.net/e1BX7M

我搜索了很多,datetime.parseexact 或 datetime.parse 仅适用于一种特定格式,例如 dd/mm/yyyy 或 mm/dd/yyyy。

示例:当我使用这样的东西时

Date.Parse(Request.QueryString("asofdate"), CultureInfo.CurrentCulture)

并且 Request.QueryString("asofdate") 格式为 dd/mm/yyyy,系统会抛出异常,否则当格式为 mm/dd/yyyy 时可以正常工作。

我也尝试过使用:

Date.Parse(Request.QueryString("asofdate"), CultureInfo.CurrentCulture)

如何将所有格式处理成一个函数?我是否必须使用 tryparse 10 次而不是使用 Date 结构中的一个集成函数?

编辑:问题:是否可以通过使用一行代码来减少 tryparse(一种格式)tryparse(第二种格式)tryparse(第三种格式)的代码。

标签: .netvb.netlocalizationglobalization

解决方案


似乎我们缺乏信息,但假设您正在使用 Web API 或控制器,您可以使用 httpContext requestCulture 功能


// Retrieves the requested culture
var feature = Request.HttpContext.Features.Get<IRequestCultureFeature>();
// information of the requested culture (assigned in the Accept-Language header
var culture = feature.RequestCulture.Culture;

Log($"current culture: {culture}")

//then

var parsedDate = DateTime.Parse(requestObject.dateValueFromJson, culture)
// warining this may cause an exception, so I suggest to use TryParse instead and handle when parsing fails.

希望能帮助到你。


推荐阅读