Reputation: 566
I have a xml which can return a time in the format (7/23/2013 4:00pm) my question is: How can I explain to DateTime.ParseExact that I'm in the "am" or in the "pm"? I have this piece of code, but it returns me an exception (String can not be parsed)
I alredy placed an example string (7/23/2013 4:00pm) in which I replace "pm" by the empty chain "".
string pattern = "MM/dd/yyyy H:mm 'UTC' zzz";
DateTime time = DateTime.ParseExact(sb.ToString(), pattern, CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal |
DateTimeStyles.AdjustToUniversal);
Thank you very much :)
Upvotes: 2
Views: 1883
Reputation: 22794
You need the tt
format:
string pattern = "MM/dd/yyyy h:mm 'UTC' tt";
DateTime time = DateTime.ParseExact(sb.ToString(), pattern, CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal |
DateTimeStyles.AdjustToUniversal);
Upvotes: 0
Reputation: 1375
You can pass an array to cover various formats. I use the following for various time inputs.
var formats = new[]
{
"M/dd/yyyy hh:mm tt",
"M/dd/yyyy hh:mmtt",
"M/dd/yyyy h:mm tt",
"M/dd/yyyy h:mmtt",
"M/dd/yyyy hhtt",
"M/dd/yyyy htt",
"M/dd/yyyy h tt",
"M/dd/yyyy hh tt"
};
var date = "7/23/2013 4:00pm";
DateTime time = DateTime.ParseExact(date, formats, CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal |
DateTimeStyles.AdjustToUniversal);
Upvotes: 6
Reputation: 2168
H
in your pattern expects the time in a 24 style. You need tt
(as outlined in the previous answer) AND you must a small h
in your pattern:
string pattern = "MM/dd/yyyy h:mm 'UTC' tt";
Upvotes: 0