c# - 如何在 ASP.Net Core 中更改路由中的 DateTime 格式?

标签 c# datetime asp.net-core .net-core datetime-format

我在 Route 属性中使用 datetime 是这样的:

[Route("{givenDate:datetime}")]

但它是“美国”格式,即“月-日-年”。

如何将其转换为“日-月-年”格式?

附言。我知道我可以使用其他格式,例如“年-月-日”或“年-月-日”,但“日-月-年”对我来说看起来更直观。

最佳答案

您可以改为使用如下路线:

[Route("{day:regex(^[[0-2]][[0-9]]|3[[0-1]]$)}-{month:regex(^0[[0-9]]|1[[0-2]]$)}-{year:regex(^\\d{{4}}$)}")]

然后将您的操作更改为:

public IActionResult Foo(int day, int month, int year)
{
    var givenDate = new DateTime(year, month, day);

    ...
}

诚然,这很糟糕,但它确实完成了工作。正则表达式约束虽然丑陋得要命,但将确保最终通过的任何值都将用于构造 DateTime 对象。

关于c# - 如何在 ASP.Net Core 中更改路由中的 DateTime 格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52963326/

相关文章:

c# - 通用约束 : Can I test Equality of generic that can be a reference or value type?

c# - XDocument Root.Elements() 返回 null

mysql - 无法将 DATETIME 列添加到 MySQL 表

.NET Core 3 System.Text.Json 嵌套对象序列化

postgresql - 为什么每秒对我的Asp.Net Core API的并发请求数增加时,响应时间会增加

c# - 从列表 C# 中删除第一个对象

c# - .netTiers + Codesmith VS Entity Framework .Net C#

java - 将 Instant 格式化为 String 时出现 UnsupportedTemporalTypeException

python-2.7 - python / Pandas : How do I convert from datetime64[ns] to datetime

c# - .net 核心类库中的不同字符编码