.net - 如何设置全局函数来为不同语言环境转换所有不同格式的日期?
问题描述
我们正在创建一个具有不同语言环境的系统。我可以说所有可以在这里找到的 .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(第三种格式)的代码。
解决方案
似乎我们缺乏信息,但假设您正在使用 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.
希望能帮助到你。
推荐阅读
- html - CSS中的溢出在数据表中不起作用
- python - Tensorflow 2.0:当输出分支到两个单独学习的模型时,错误如何反向传播到层?
- terraform - 如何在 terraform 输出变量中附加到根模块中的列表?
- r - 通过字符变量将一列分成两列
- php - 将使用 FPDF 创建的 pdf 插入/保存到数据库中
- javascript - 有没有办法让 chrome 扩展在标签之间独立运行?
- assembly - 在调用 printf 的循环中与 nasm 中的 mul 相乘 - 结果意外增长
- vb.net - VB.net 中的数据网格视图值
- java - 在 html 的帮助下在 java 中创建一个多色的 JLabel
- ios - 如何阅读符号化的崩溃日志?