C # output format: DateTime.Now Month

In this C # code snippet, DateTime.Now.Month.ToString() returns 7 as output.

I would like to get 07 as the return value.

What can I do to add a leading zero when a month has only 1 digit?

+63
c #
Jul 20 '09 at 9:25
source share
6 answers
 DateTime.Now.Month.ToString("d2") 
+112
Jul 20 '09 at 9:26 a.m.
source share
— -

Format a two-digit integer, as suggested by Mehrdad, or format DateTime itself to give you a two-digit month:

 DateTime.Now.ToString("MM") 
+49
Jul 20 '09 at 9:33
source share

I use Selenium Webdriver to test a website and set various variables, strings, etc .; this made it a lot easier:

 /* Date strings */ public static string TodayNum = DateTime.Now.ToString("dd"); // eg 07 public static string ThisMonthNum = DateTime.Now.ToString("MM"); // eg 03 public static string ThisMonthShort = DateTime.Now.ToString("MMM"); // eg Mar public static string ThisMonthLong = DateTime.Now.ToString("MMMM"); // eg March public static string ThisYearNum = DateTime.Now.ToString("yyyy"); // eg 2014 
+14
Mar 27 '14 at 13:24
source share

You can use: DateTime.Now.Month.ToString().PadLeft(2, '0');

He will return: 07

+4
Mar 31 '14 at 5:18
source share

You can also convert the month and day into a two-digit number by following the following functions:

 System.DateTime.Now.Month.ToString("00") //Give 01 for January System.DateTime.Now.Day.ToString("00") 
+3
Jan 27 '17 at 10:52 on
source share

I need alphabetical characters for a month, for example: for January I need the letter A, for February I need the letter B, for ma

0
May 18 '19 at 8:37
source share



All Articles