C#:DateTime.Now月输出格式

时间:2009-07-20 09:25:55

标签: c#

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

我想将07作为返回值。

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

5 个答案:

答案 0 :(得分:113)

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

答案 1 :(得分:49)

根据Mehrdad的建议格式化两位数的整数,或格式化DateTime本身给你一个两位数的月份:

DateTime.Now.ToString("MM")

答案 2 :(得分:14)

我正在使用Selenium Webdriver测试网站并在开始时设置各种变量,字符串等;这使它变得更简单:

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

答案 3 :(得分:4)

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

它将返回:07

答案 4 :(得分:3)

您也可以通过以下功能将月和日转换为两位数:

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