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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1152583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 09:28:24  来源:igfitidea点击:

C#:DateTime.Now Month output format

c#

提问by Shyju

In this C# code snippet, DateTime.Now.Month.ToString()returns 7as output.

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

I would like to get 07as a return value.

我想得到07一个返回值。

What can I do to add the leading zero when the month has only 1 digit?

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

采纳答案by Mehrdad Afshari

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

回答by Jon Skeet

Either format the integer with two digits as suggested by Mehrdad, or format the DateTimeitself to give you a two-digit month:

要么按照 Mehrdad 的建议用两位数格式化整数,要么格式化它DateTime本身以给您一个两位数的月份:

DateTime.Now.ToString("MM")

回答by Amoz

I'm using Selenium Webdriver to test a website and set various vars, strings, etc. at the beginning; this made it a lot simpler:

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

回答by Naveed Mansuri

You could use: DateTime.Now.Month.ToString().PadLeft(2, '0');

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

It will return: 07

它将返回: 07

回答by Romil Kumar Jain

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")