Reputation: 1347
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
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
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
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:
{0:yyyy-MM-dd}
. The 0:
is necessary.string
, so the format string yyyy-MM-dd
has no meaning there.Upvotes: 1
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
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");
Upvotes: 1