C#:DateTime.Now月份输出格式

在这个C#代码片段中, DateTime.Now.Month.ToString()返回7作为输出。

我想得到07作为返回值。

当月份只有1位数字时,我可以做些什么来添加前导零?

 DateTime.Now.Month.ToString("d2") 

或者按照Mehrdad的build议格式化两位数的整数,或者将DateTime自身格式化为两位数的月份:

 DateTime.Now.ToString("MM") 

谢谢,正是我所需要的。 我使用Selenium Webdrivertesting一个网站,并在开始时设置各种variables/string等,这使得它更简单了,我现在使用的代码是:

  /* 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 

你可以使用: DateTime.Now.Month.ToString().PadLeft(2, '0');

它将返回: 07

您也可以通过以下function将月份和date转换为两位数字:

 System.DateTime.Now.Month.ToString("00") //Give 01 for January System.DateTime.Now.Day.ToString("00")