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
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.
string date = DateTime. ParseExact(SourceDate, "dd/MM/yyyy", CultureInfo. InvariantCulture). ToString("yyyy-MM-dd");
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With