52

I want to convert the DateTime.Now to the format of yyyy-mm-dd since that is the only format that i can use in my query that i want to include.
The default format of DateTime.Now looks like 5/1/2008 6:32:06 PM.
If i want to change the format of it to yyyyMMdd I could use this line of code:

var dateString1 = DateTime.Now.ToString("yyyyMMdd");

But, when i try the same for this yyyy-mm-dd format like below:

var dateString2 = DateTime.Now.ToString("yyyy-mm-dd");

the result i get is wrong. For the following lines of code:

var dateString1 = DateTime.Now.ToString("yyyyMMdd");
var dateString2 = DateTime.Now.ToString("yyyy-mm-dd");

Console.WriteLine("yyyyMMdd " + dateString1);
Console.WriteLine("yyyy-mm-dd "+ dateString2);

I get the following result:

enter image description here

which is wrong for the second case.
What am i missing?

Community
  • 1
  • 1
etrupja
  • 2,710
  • 6
  • 22
  • 37
  • 2
    `mm` is minutes. What you need is `MM` as in your first format. – uTeisT Aug 08 '16 at 07:50
  • Does this answer your question? [How to convert any date format to yyyy-MM-dd](https://stackoverflow.com/questions/12257483/how-to-convert-any-date-format-to-yyyy-mm-dd) – Yousha Aleayoub Jan 12 '23 at 10:43

3 Answers3

75

According to msdn MM format specifier stands for month and mm - for minutes.

"mm" | The minute, from 00 through 59.

"MM" | The month, from 01 through 12.

So your code should look like the following:

    var dateString1 = DateTime.Now.ToString("yyyyMMdd");
    var dateString2 = DateTime.Now.ToString("yyyy-MM-dd");

    Console.WriteLine("yyyyMMdd " + dateString1);
    Console.WriteLine("yyyy-MM-dd "+ dateString2);

And you will get the desired result

Mikhail Tulubaev
  • 4,141
  • 19
  • 31
20
    var dateString1 = DateTime.Now.ToString("yyyyMMdd");
    var dateString2 = DateTime.Now.ToString("yyyy-MM-dd");

    Console.WriteLine("yyyyMMdd " + dateString1);
    Console.WriteLine("yyyy-MM-dd "+ dateString2);

You are using "mm" instead of "MM" in your second format. mm is for minutes, MM is for month.

Bojan B
  • 2,091
  • 4
  • 18
  • 26
  • Thanks for your solution. This solved my problem but @Mikhail explained the reason so I accepted his answer and up voted yours, too. Thanks – etrupja Aug 08 '16 at 08:09
5

Your miss is lower-case "m" in second format, that determine MINUTES, but you need "M" instead of "m" for MONTHS.

Nigrimmist
  • 10,289
  • 4
  • 52
  • 53