在 C# 中获取当前月份数的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8777701/
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-09 04:23:30  来源:igfitidea点击:

Best way to get the current month number in C#

c#stringdatetime

提问by user386258

I am using C# to get current month number:

我正在使用 C# 来获取当前月份数:

string k=DateTime.Now.Month.ToString();

For January it will return 1, but I need to get 01. If December is the current month, I need to get 12. Which is the best way to get this in C#?

一月份它会回来1,但我需要得到01。如果 12 月是当月,我需要得到12. 在 C# 中获得它的最佳方法是什么?

采纳答案by Shai

string sMonth = DateTime.Now.ToString("MM");

回答by Oded

Lots of different ways of doing this.

有很多不同的方法来做到这一点。

For keeping the semantics, I would use the Monthproperty of the DateTimeand format using one of the custom numeric format strings:

为了保持语义,我将使用自定义数字格式字符串之一MonthDateTime和格式的属性:

DateTime.Now.Month.ToString("00");

回答by Mark PM

DateTime.Now.Month.ToString("0#")

回答by DRapp

use string formatting... the "0" is a specific place-holder to be shown of the expected value

使用字符串格式......“0”是一个特定的占位符,用于显示预期值

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

回答by Farooq Alsaegh

    using System;

class Program
{
    static void Main()
    {
    //
    // Get the current month integer.
    //
    DateTime now = DateTime.Now;
    //
    // Write the month integer and then the three-letter month.
    //
    Console.WriteLine(now.Month);
    Console.WriteLine(now.ToString("MMM"));
    }
}

Output

输出

5

5

May

可能