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?

5
  • 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? Commented Mar 21, 2019 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 Commented Mar 21, 2019 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 Commented Mar 21, 2019 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? Commented Mar 21, 2019 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. Commented Mar 21, 2019 at 21:31

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

I thought that display attribute way only set the default display format. can it also be used to set the parse format?
if using get { DateTime.ParseExact(someDateTime, "dd MMM yyyy HH:mm:ss", CultureInfo.InvariantCulture); } surely i would be using set (not get)
@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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.