How to change DateTime format in route in ASP.Net Core?

Viewed 615

I'm using datetime in Route attribute like that:

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

but it's in "American" format which is "month-day-year".

How can I convert it to "day-month-year" format?

PS. I'm aware that I can use other formats like "yearmonthday" or "year-month-day", but "day-month-year" looks more intuitive for me.

1 Answers

You could instead use a route like:

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

And then change your action to something like:

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

    ...
}

Admittedly, that kind of sucks, but it does get the job done. The regex constraints, while ugly as hell, will ensure that ultimately any values that get through will work to construct a DateTime object with.

Related