user386258
user386258

Reputation: 1953

Best way to get the current month number in C#

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

Answers (4)

Farooq Alsaegh
Farooq Alsaegh

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

Mark PM
Mark PM

Reputation: 2919

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

Upvotes: 0

Oded
Oded

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

Shai
Shai

Reputation: 25619

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

Upvotes: 71

Related Questions