Jacko
Jacko

Reputation: 13195

Why does String.Format convert a forward slash into a minus sign?

Why does String.Format("/") get converted to "-"?

Upvotes: 15

Views: 7078

Answers (4)

Mark Hall
Mark Hall

Reputation: 54532

It looks like your date seperator in your culture is "-" instead of "/". see msdn and this article

Edit:

Have you checked your region and Language settings to make sure you do not have an option selected that uses the "-".

enter image description here

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500275

As per Custom Date and Time Format Strings, / refers to the culture's date separator. So you need to escape it. You can either use a backslash as per Darin's answer, or you can quote it in single quotes. For example:

using System;
using System.Globalization;

class Test
{
    static void Main()
    {
        DateTime date = DateTime.Now;

        CultureInfo da = new CultureInfo("da");
        // Prints 09-08-2011
        Console.WriteLine(string.Format(da, "{0:dd/MM/yyyy}", date));
        // Prints 09/08/2011
        Console.WriteLine(string.Format(da, "{0:dd'/'MM'/'yyyy}", date));
        // Prints 09/08/2011
        Console.WriteLine(string.Format(da, "{0:dd\\/MM\\/yyyy}", date));
    }
}

Upvotes: 13

Guffa
Guffa

Reputation: 700272

I tried that with all possible cultures:

foreach (CultureInfo info in CultureInfo.GetCultures(CultureTypes.AllCultures)) {
  Console.Write(String.Format(info, "/"));
}

Output:

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////

So, that doesn't happen anywhere.

Upvotes: 6

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

I suspect that you are using the / symbol inside a {0} placeholder. It is a reserved symbol used as datetime separator in the given culture. You could escape it, like this:

string date = string.Format("{0:dd\\/MM\\/yyyy}", DateTime.Now);

Upvotes: 23

Related Questions