kumar
kumar

Reputation: 2944

How to convert a string containing a date to a different format?

Consider this string

11/12/2010

I need to convert this to 20101112.

How can this be done?

Upvotes: 3

Views: 248

Answers (2)

David
David

Reputation: 73574

Given that the first is a valid date, and the second is a different representation of the date, the easiest method with the least amount of code for your example is:

string newString = DateTime.ParseExact("11/12/2010", "MM/dd/yyyy").ToString("yyyyMMdd")

Upvotes: 6

Ben Gribaudo
Ben Gribaudo

Reputation: 5147

Try this:

string input = "11/12/2010";
DateTime date = DateTime.Parse(input);
string formattedOutput = date.ToString("yyyyMMdd");

The above as a one-liner:

string formattedOutput = DateTime.Parse("11/12/2010").ToString("yyyyMMdd");

Upvotes: 1

Related Questions