C#:DateTime.Now Month输出格式


72

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

我想07作为返回值。

当月份只有1位数字时,我该怎么做才能添加前导零?

Answers:



52

按照Mehrdad的建议,用两位数字格式化整数,或者格式化DateTime自己的位数以得到两位数的月份:

DateTime.Now.ToString("MM")

22

我正在使用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

即使删除了绒毛,这也不是真正解决问题的方法。
TylerH

4

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

它将返回: 07


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.