【发布时间】:2012-01-08 12:57:08
【问题描述】:
我正在使用 C# 获取当前月份数:
string k=DateTime.Now.Month.ToString();
一月份它会返回1,但我需要得到01。如果 12 月是当前月份,我需要获取 12。在 C# 中获得此功能的最佳方法是什么?
【问题讨论】:
我正在使用 C# 获取当前月份数:
string k=DateTime.Now.Month.ToString();
一月份它会返回1,但我需要得到01。如果 12 月是当前月份,我需要获取 12。在 C# 中获得此功能的最佳方法是什么?
【问题讨论】:
string sMonth = DateTime.Now.ToString("MM");
【讨论】:
有很多不同的方法。
为了保持语义,我将使用DateTime 的Month 属性并使用custom numeric format strings 之一进行格式化:
DateTime.Now.Month.ToString("00");
【讨论】:
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
五月
【讨论】:
DateTime.Now.Month.ToString("0#")
【讨论】: