tags:

views:

153

answers:

4

Hi,

I've got DateTime variable and i want to convert it to string "DD.MM.YYYY" Please note, the values must be separated by "dot" sign.

Of course I can do manual string composition. But I wonder if I can use DateTime.ToString() to do required conversion.

+8  A: 

Yes, you can use DateTime.ToString like this:

myDateVariable.ToString("dd.MM.yyyy");

Note that you have to use capital MM here, since mm evaluates to minutes instead of months.

Øyvind Bråthen
+9  A: 

Yes, you can:

string formatted = dt.ToString("dd'.'MM'.'yyyy");

Now in this case the quotes aren't actually required, as custom date/time format strings don't interpret dot in any special way. However, I like to make it explicit - if change '.' for ':' for example, then while it's quoted it will stay with the explicit character, but unquoted it would be "the culture-specific time separator". It wasn't entirely obvious to me whether "." would be interpreted as "the culture-specific decimal separator" or not, hence the quoting. You may feel that's over the top, of course - it's entirely your decision.

You may also want to specify the invariant culture, just to remove any other traces of doubt:

string formatted = dt.ToString("dd'.'MM'.'yyyy", CultureInfo.InvariantCulture);

(At that point the quotes around the dot become less relevant, as "." is the decimal separator in the invariant culture anyway.)

Jon Skeet
+1: Thanks for the detailed information regarding the quotes any their meaning in this case.
Øyvind Bråthen
+1  A: 

You can format the date like this:

date.ToString("dd.MM.yyyy")

When formatting numbers the period . will change depending on the CultureInfo used, but not when formatting dates.

If you are verifying your code against the code analysis rule CA1304: Specify CultureInfo you will have to use the invariant culture even though it doesn't matter for this particular format:

date.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture)
Martin Liversage
+3  A: 

Here's an alternative for you:

DateTime.Now.ToString("d", new CultureInfo("de-DE"))

German's use . as the date separator.

Naeem Sarfraz
Do you really want everyone reading the code to have to know that though? Isn't it simpler to spell it out?
Jon Skeet
Also, I believe it's possible to override any culture with your own settings, so that's not guaranteed behaviour.
Dan Puzey
note the word **alternative**, thanks for the heads up anyway
Naeem Sarfraz