Reputation: 57
How can I parse this DateTime
value?
17-09-2018 3:18
I want to parse the date and the time. This is what I've tried so far:
x = DateTime.ParseExact(dateString, "d/M/yyyy hh:MM",CultureInfo.InvariantCulture).ToString();
x = DateTime.ParseExact(dateString, "dd/MM/yyyy hh:MM",CultureInfo.InvariantCulture).ToString();
x = DateTime.ParseExact(dateString, "dd/MM/yyyy hh:MM",CultureInfo.InvariantCulture).ToString();
How can I make this work?
Upvotes: 1
Views: 1841
Reputation: 62213
MM
is months, mm
is minutes. The casing matters. m
or double M
means the value always has 2 digits. A single m
or single M
means the value can have 1 digit if below 10
.H
means hours in military time (24 hour format), h
means 12 hour with possible am/pm. The same rule applies for double digits.-
if you are using /
or the other way around. Alternativly use a culture parameter that has the same format specifier as in the input string. DateTime x = DateTime.ParseExact("17-09-2018 3:18", "d-MM-yyyy h:m", CultureInfo.InvariantCulture);
See also DateTime.ParseExact and Custom Date and Time Format Strings
Upvotes: 5
Reputation: 174
You are almost there. You just need to remember two more things:
It's better to use DateTime.TryParseExact and not let the program throw exception interrupting the flow unless that is intended.
// input string
string dateString = "5/01/2009 09:00";
// variable to hold output value
DateTime dateValue;
// specify all the valid formats here applicable in your case
string[] formats = { "dd/MM/yyyy hh:mm", "dd/M/yyyy hh:mm", "d/M/yyyy hh:mm", "d/MM/yyyy hh:mm", "dd/MM/yy hh:mm", "dd/M/yy hh:mm", "d/M/yy hh:mm", "d/MM/yy hh:mm"};
if (DateTime.TryParseExact(dateString, formats, CultureInfo.InvariantCulture,
DateTimeStyles.None, out dateValue))
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue,
dateValue.Kind);
Upvotes: 0