C#:DateTime.Now Month output format
Solution 1:
DateTime.Now.Month.ToString("d2")
Solution 2:
Either format the integer with two digits as suggested by Mehrdad, or format the DateTime
itself to give you a two-digit month:
DateTime.Now.ToString("MM")
Solution 3:
I'm using Selenium Webdriver to test a website and set various vars, strings, etc. at the beginning; this made it a lot simpler:
/* Date strings */
public static string TodayNum = DateTime.Now.ToString("dd"); // e.g 07
public static string ThisMonthNum = DateTime.Now.ToString("MM"); // e.g 03
public static string ThisMonthShort = DateTime.Now.ToString("MMM"); // e.g Mar
public static string ThisMonthLong = DateTime.Now.ToString("MMMM"); // e.g March
public static string ThisYearNum = DateTime.Now.ToString("yyyy"); // e.g 2014
Solution 4:
You could use: DateTime.Now.Month.ToString().PadLeft(2, '0');
It will return: 07
Solution 5:
You can also convert Month and Day to two digit number by following functions too:
System.DateTime.Now.Month.ToString("00") //Give 01 for January
System.DateTime.Now.Day.ToString("00")