Reputation: 9738
I have the hidden
field in my View
which is in List foreach
Loop.
@Html.HiddenFor(m => m[i].List[q].EntryDate)
I want the format
of this hidden field to be dd/MM/yyyy
. Currently when the data is binded this date also includes time.
I have used a global UTCDateTimeModelBinder
which parses datetime model value like this :-
var dt = DateTime.ParseExact(value.AttemptedValue.Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
So it gives me error if the time is present in the datetime model value.
Upvotes: 0
Views: 1735
Reputation: 320
You are receiving an error because the format you have specified does not match the input string. If you are not concerned with the time part of the string then simply:
var dt = DateTime.ParseExact(value.AttemptedValue.Trim().Substring(0,10), "dd/MM/yyyy", CultureInfo.InvariantCulture);
Upvotes: 0
Reputation: 98740
If there are more than one possible formats for your inputs, you can use DateTime.ParseExact(String, String[], IFormatProvider, DateTimeStyles)
overload which takes your formats as a string array.
string[] formats = new string[]{"dd/MM/yyyy", "dd/MM/yyyy HH:mm:ss"};
var dt = DateTime.ParseExact(value.AttemptedValue.Trim(), formats,
CultureInfo.InvariantCulture, DateTimeStyles.None);
Upvotes: 2