Santanor
Santanor

Reputation: 566

Parsing DateTime to Universal Time C#

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

Answers (3)

It'sNotALie.
It'sNotALie.

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

LUKE
LUKE

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

Jan
Jan

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

Related Questions