3

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.

Morasiu
  • 1,204
  • 2
  • 16
  • 38
  • Possible duplicate of https://stackoverflow.com/questions/919244/converting-a-string-to-datetime question. – AndrasCsanyi Oct 24 '18 at 07:40
  • 2
    I don't think so. I know to change DateTime formats, but i don't know how to set this in `Route` attribute :) – Morasiu Oct 24 '18 at 07:44
  • 2
    It doesn't look like you can change the `datetime` constraint: See the [docs](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-2.1#route-constraint-reference), notably the warning at the bottom of the linked section. – Kirk Larkin Oct 24 '18 at 07:47
  • Ohh... That's a shame I guess. But thank you – Morasiu Oct 24 '18 at 07:57

1 Answers1

3

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.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444