0

I understand that if you want to parse a dateTime String in a specific format when converting it to a DateTime object you do this

DateTime someDateTime = DateTime.ParseExact(myDateTime , "dd MMM yyyy HH:mm:ss", CultureInfo.InvariantCulture);

However when using a model binding with MVC C# the code is declared like this

public DateTime someDateTime {get; set;}

When doing this how do you set the format which incoming date string are expected to have?

megaman
  • 1,035
  • 1
  • 14
  • 21
  • Do you *absolutely* have to do this? I'd expect the model binding to be in a machine-readable format, typicaly ISO-8601. Is there any reason you'd need something else here? – Jon Skeet Mar 21 '19 at 20:26
  • I though ISO-8601 is a standard for setting the format not a fixed format. ie you could set yyyy/mm/dd hh:mm or yy-m-D hh:MM:ss or countless other variations – megaman Mar 21 '19 at 20:50
  • No, ISO-8601 is a specific format. (There are variants, such as whether it's 20190321T205500 or 2019-03-21T20:55:00 for example.) But "yyyy/mm/dd hh:mm" is *not* ISO-8601 – Jon Skeet Mar 21 '19 at 20:55
  • are you saying that i can assume that the DateTime object in the MVC model-property binding will expect ISO-8601 by default and i need to make sure what i am submitting is in that format? – megaman Mar 21 '19 at 21:15
  • That's what I'd *expect*, and it's definitely worth trying first. That's the most reasonable, standardized format to use. – Jon Skeet Mar 21 '19 at 21:31

1 Answers1

0

You can have a separate property for having the formatted version of the date:

public DateTime someDateTime { get; set; }

public DateTime someDateTimeFormatted {
    get {
        DateTime.ParseExact(someDateTime, "dd MMM yyyy HH:mm:ss", CultureInfo.InvariantCulture);
    }
}

If the date you're trying to serialize will not naturally serialize into a datetime you can write a custom serialization for it of you can pass it in the request as a string and parse it in a getter of a diff model property similar to what someDateTimeFormatted is doing above

GregH
  • 5,125
  • 8
  • 55
  • 109
  • I thought that display attribute way only set the default display format. can it also be used to set the parse format? – megaman Mar 21 '19 at 20:45
  • if using get { DateTime.ParseExact(someDateTime, "dd MMM yyyy HH:mm:ss", CultureInfo.InvariantCulture); } surely i would be using set (not get) – megaman Mar 21 '19 at 20:48
  • @megaman it only needs a getter and acts on the value of the non-formatted property which is the one that has the set... ive edited my answer to try and make this more clear – GregH Mar 22 '19 at 01:32