【问题标题】:How to change DateTime format in route in ASP.Net Core?如何在 ASP.Net Core 中更改路由中的 DateTime 格式?
【发布时间】:2018-10-24 07:36:41
【问题描述】:

我在 Route 属性中使用了 datetime,如下所示:

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

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

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

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

【问题讨论】:

  • 我不这么认为。我知道要更改 DateTime 格式,但我不知道如何在 Route 属性中设置它:)
  • 您似乎无法更改datetime 约束:请参阅docs,尤其是链接部分底部的警告。
  • 哦...我猜这很可惜。不过谢谢

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


【解决方案1】:

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

[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 对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-22
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    • 2017-01-08
    • 2018-01-30
    • 2022-01-16
    相关资源
    最近更新 更多