Format DateTime.Now to yyyy-mm-dd

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

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

But, when I try to do the same for this yyyy-mm-dd format, as shown below:

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

The result that I got is incorrect. 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 not true for the second case.
What am I missing?

+5
source share
3 answers

According to msdn MM a format specifier means a month and MM means a few minutes.

"mm" | Minute, 00 to 59.

"MM" | Month, from 01 to 12.

So your code should look like this:

  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

+7
source
  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 use "mm" instead of "MM" in the second format. mm is minutes, MM is month.

+7
source

Your miss is the lowercase "m" in the second format, which defines MINUTES, but you need "M" instead of "m" for MONTHS.

+2
source

All Articles