Nergon
Nergon

Reputation: 453

Convert a string to DateTime in C#

I am trying to convert a string to a DateTime for some hours now, The string looks like this

"20140519-140324" and I know its in UTC

I've allready tried this

DateTime ourDateTime;
bool success = DateTime.TryParseExact(Date, "yyyy-MM-dd-HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out ourDateTime);
StartTime.Text = ourDateTime.ToString("g");

and this

DateTime ourDateTime= DateTime.ParseExact(Date, "yyyy-MM-dd-HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
StartTime.Text = ourDateTime.ToString("g");

but none of these work. What I am not doing properly?

Upvotes: 1

Views: 1403

Answers (2)

Soner Gönül
Soner Gönül

Reputation: 98750

From DateTime.TryParseExact method

Converts the specified string representation of a date and time to its DateTime equivalent. The format of the string representation must match a specified format exactly.

In your example, they are not. Use yyyyMMdd-HHmmss custom format instead which exactly matches with your string.

Here an example on LINQPad;

string s = "20140519-140324";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyyMMdd-HHmmss", CultureInfo.InvariantCulture,
                          DateTimeStyles.AdjustToUniversal, out dt))
{
    dt.Dump();
}

Here a demonstration.

Your DateTime.ParseExact example also won't work because of the same reason.

For more information;

Upvotes: 5

Zohar Peled
Zohar Peled

Reputation: 82474

You are using the wrong format in the TryParseExact method. the format parameter should be an indicator to the format of the input string. therefor you need to do this:

DateTime ourDateTime;
bool success = DateTime.TryParseExact(Date, "yyyyMMdd-HHmmss", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out ourDateTime);
if(success) {
    StartTime.Text = ourDateTime.ToString("g");
}

Upvotes: 1

Related Questions