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

use*_*258 25 c# string datetime

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

string k=DateTime.Now.Month.ToString();
Run Code Online (Sandbox Code Playgroud)

一月它会回来1,但我需要得到01.如果12月是当月,我需要得到12.哪个是在C#中获得此功能的最佳方式?

Sha*_*hai 53

string sMonth = DateTime.Now.ToString("MM");
Run Code Online (Sandbox Code Playgroud)


Ode*_*ded 9

有很多不同的方法可以做到这一点.

为了保持语义,我会使用Month的财产DateTime使用的一个和格式的自定义数字格式字符串:

DateTime.Now.Month.ToString("00");
Run Code Online (Sandbox Code Playgroud)


小智 8

    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"));
    }
}
Run Code Online (Sandbox Code Playgroud)

输出

5

可能