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

时间:2012-01-08 12:57:08

标签: c# string datetime

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

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

1月份它会返回1,但我需要01。如果12月是当月,我需要12。哪种是在C#中获得此功能的最佳方式?

5 个答案:

答案 0 :(得分:49)

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

答案 1 :(得分:9)

有很多不同的方法。

为了保持语义,我会使用Month的{​​{1}}属性并使用custom numeric format strings之一进行格式化:

DateTime

答案 2 :(得分:3)

使用字符串格式化...“0”是要显示预期值的特定占位符

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

答案 3 :(得分:3)

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

输出

5

答案 4 :(得分:0)

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