在此C#代码段中,作为输出DateTime.Now.Month.ToString()返回7。
我想07作为返回值。
当月份只有1位数字时,我该怎么做才能添加前导零?
Answers:
我正在使用Selenium Webdriver来测试网站并在开始时设置各种var,字符串等。这使事情变得简单得多:
/* 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
您可以使用: DateTime.Now.Month.ToString().PadLeft(2, '0');
它将返回: 07
您也可以通过以下功能将月份和日期转换为两位数:
System.DateTime.Now.Month.ToString("00") //Give 01 for January
System.DateTime.Now.Day.ToString("00")