Reputation: 383
I'm trying to format a DateTime in a C# function, but I can't get it to work.
The format I'm trying to get is like this:
"28/02/2012"
I've tried different ways to format the DateTime, for example:
string formattedDate = DateTime.Today.ToString("dd/MM/yyyy");
string formattedDate = String.Format("{0:dd/MM/yyyy}", DateTime.Today);
Both these examples are giving me this result:
"28.02.2012"
I've formatted DateTimes many times before using the two ways shown above, but I can't really see why I'm getting "." instead of "/".
Is there some configuration that has to be set up or something?
Upvotes: 3
Views: 4008
Reputation: 7788
I did it like this:
string formattedDate = (String.Format("{0:dd.MM.yyyy}", DateTime.Today)).Replace(".", @"/");
Upvotes: 0
Reputation: 43056
The /
character in a date-time format string is a placeholder for the culture-specific date separator. To specify the /
character explicitly, you need to escape it: "dd\\/MM\\/yyyy"
or @"dd\/MM\/yyyy"
For more information, see the MSDN page "Custom Date and Time Format Strings"
Upvotes: 6
Reputation: 1503280
phoog has given the correct reason, but I would suggest the wrong workaround. If you always want to format the date/time as if you were in a particular culture (probably the invariant culture) then you can do that:
string formattedDate = DateTime.Today.ToString("dd/MM/yyyy",
CultureInfo.InvariantCulture);
I find this cleaner than forcing some parts of the format into an invariant form, while leaving others (the numbers) up to the culture. For example, consider this:
using System;
using System.Globalization;
using System.Threading;
class Test
{
static void Main()
{
CultureInfo ci = new CultureInfo("ar-SA");
Thread.CurrentThread.CurrentCulture = ci;
string formattedDate = DateTime.Today.ToString("dd/MM/yyyy");
Console.WriteLine(formattedDate);
}
}
Today, that prints "06/04/1433" - which is appropriate for the Islamic calendar, but probably isn't what you expected.
Upvotes: 11