user222427
user222427

Reputation:

C# convert DateTime from one format to another

I thought this would be a really simple, and i've tried to google it and I keep getting the exception String was not recognized as a valid DateTime.

This is my value "2013-10-21T14:10:49" this is what I want to convert it into 10/21/2013 10:49

string sample = "2013-10-21T14:10:49";
DateTime date31 = DateTime.ParseExact(sample, "MM/dd/yyyy HH:mm", System.Globalization.CultureInfo.InvariantCulture);

Upvotes: 2

Views: 4718

Answers (3)

Jensen
Jensen

Reputation: 3538

You don't need the ParseExact method, the Parse method is sufficient because it allows your date representation. See DateTime - The string to parse for an overview of allowed input formats.

This means the following works:

string sample = "2013-10-21T14:10:49";
DateTime parsed = DateTime.Parse(sample);

Console.WriteLine(parsed.ToString("MM/dd/yyyy HH:mm:ss"));

And the result is:

10/21/2013 14:10:49

Upvotes: 1

Tim S.
Tim S.

Reputation: 56536

When you write DateTime.ParseExact(sample, "MM/dd/yyyy HH:mm", ...), you are saying that sample is in the format MM/dd/yyyy HH:mm. Since it is not, it throws an exception.

It's important to know that a DateTime does not have any format associated with it. It's only when you convert it to or from a string that format can come into play. You should probably use something like this:

string sample = "2013-10-21T14:10:49";
DateTime date31 = DateTime.Parse(sample, System.Globalization.CultureInfo.InvariantCulture);
string date31string = date31.ToString("MM/dd/yyyy HH:mm", System.Globalization.CultureInfo.InvariantCulture);
// date31string is "10/21/2013 14:10"

Instead of ParseExact, I used Parse, since the format is recognized by Parse, and I don't see much point in limiting what sort of formats it can accept to only that particular format.

Upvotes: 3

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

Your string appears to be in format of "Xml-serialized". So it is the job of XmlConvert.

string sample = "2013-10-21T14:10:49";
string converted = XmlConvert.ToDateTime(sample, XmlDateTimeSerializationMode.Unspecified)
     .ToString("MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture);

Upvotes: 2

Related Questions