36

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#?

4 Answers 4

70
string sMonth = DateTime.Now.ToString("MM");
2
  • What if we need to get the MM for any other month? Oct 27, 2016 at 6:51
  • 1
    @AlokRajasukumaran someDate.ToString("MM yyyy")
    – Sonic Soul
    Jul 25, 2017 at 20:31
11

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

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.