Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue DateTime.ToString with string format "M" in .NET

I have a problem with the string format of DateTime. I think it is bug in MS. Can you explain it, and what is wrong?

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(DateTime.Now.ToString("M"));//return 07 July   <---- WRONG, SEE MSDN
        Console.WriteLine(DateTime.Now.ToString(".M"));//return .7   <---- GOOD
        Console.ReadKey();
    }
}

MSDN

like image 551
Musketyr Avatar asked Jul 09 '14 10:07

Musketyr


People also ask

How do I change the date format in ToString?

Use the DateTime. ToString() method to convert the date object to string with the local culture format. The value of the DateTime object is formatted using the pattern defined by the DateTimeFormatInfo. ShortDatePattern property associated with the current thread culture.

How do I change the date format from yyyy mm dd in C#?

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


1 Answers

From The "M" Custom Format Specifier

If the "M" format specifier is used without other custom format specifiers, it is interpreted as the "M" standard date and time format specifier. For more information about using a single format specifier, see Using Single Custom Format Specifiers later in this topic.

From Using Single Custom Format Specifiers

A custom date and time format string consists of two or more characters. Date and time formatting methods interpret any single-character string as a standard date and time format string. If they do not recognize the character as a valid format specifier, they throw a FormatException. For example, a format string that consists only of the specifier "h" is interpreted as a standard date and time format string. However, in this particular case, an exception is thrown because there is no "h" standard date and time format specifier.

To use any of the custom date and time format specifiers as the only specifier in a format string (that is, to use the "d", "f", "F", "g", "h", "H", "K", "m", "M", "s", "t", "y", "z", ":", or "/" custom format specifier by itself), include a space before or after the specifier, or include a percent ("%") format specifier before the single custom date and time specifier.

That's why you can use one of these;

Console.WriteLine(DateTime.Now.ToString(" M")); // 7
Console.WriteLine(DateTime.Now.ToString("M ")); //7
Console.WriteLine(DateTime.Now.ToString("%M")); //7
like image 141
Soner Gönül Avatar answered Nov 06 '22 06:11

Soner Gönül