M. X
M. X

Reputation: 1347

Converting a date string in C#

I have a date string with the format "dd.MM.yyyy" (eg. "01.02.2004") and want to convert it to "yyyy-MM-dd" with String.Format(...) or DateTime.ParseExact(...) or whatelse. Actually I only get exceptions. So the usage of the following code doesn't work:

String dateString = "01.02.2004";
datestring = String.Format("{yyyy-MM-dd}", dateString);

What is wrong with that? Is there an alternative with DateTime.ParseExact(..)?

Upvotes: 1

Views: 227

Answers (5)

SLaks
SLaks

Reputation: 887275

You need to parse it into a DateTime, then call ToString() with a different format:

DateTime date = DateTime.ParseExact(dateString, "dd.MM.yyyy", CultureInfo.InvariantCulture);
date.ToString("yyyy-MM-dd")

Upvotes: 4

Marius Bancila
Marius Bancila

Reputation: 16318

You're parsing a string as argument to String.Format? What do you expect out of it?

You should do something like this:

try
{
 var date = DateTme.ParseExact("yyyy.MM.dd", dateString, CultureInfo.InvariantCulture);
 var result = date.ToString("yyyy-MM-dd");
}
catch(Exception e) { /* ... */}

Upvotes: 1

JLRishe
JLRishe

Reputation: 101652

String dateString = "01.02.2004";
dateString = DateTime.ParseExact(dateString, "dd.MM.yyyy", CultureInfo.InvariantCulture)
                     .ToString("yyyy-MM-dd");

What's wrong with your attempt is:

  • When using a format string, the items need to be listed in a format like {0:yyyy-MM-dd}. The 0: is necessary.
  • When you're using string.Format(), the variable is a string, so the format string yyyy-MM-dd has no meaning there.

Upvotes: 1

Jharis
Jharis

Reputation: 42

You need to create a Datetime object first.

try something like:

DateTime t = DateTime.parse("01.02.2004");
String result = t.ToString("{yyyy-MM-dd}", CultureInfo.InvariantCulture);

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460048

You have to convert it to a DateTime first with an appropriate CultureInfo:

String dateString = "01.02.2004";
var deCulture = System.Globalization.CultureInfo.CreateSpecificCulture("de-DE");
DateTime dt = DateTime.Parse(dateString, deCulture);
dateString = dt.ToString("yyyy-MM-dd"); 

Demo

Upvotes: 1

Related Questions