Reputation: 1953
I am using C# to get current month number:
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#?
Upvotes: 37
Views: 111998
Reputation: 161
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
May
Upvotes: 9
Reputation: 498914
Lots of different ways of doing this.
For keeping the semantics, I would use the Month
property of the DateTime
and format using one of the custom numeric format strings:
DateTime.Now.Month.ToString("00");
Upvotes: 11