Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 426
user386258 Avatar asked Jan 08 '12 12:01

user386258


People also ask

How to get current month in c sharp?

To display current month, firstly use “Now“ to get the current date. DateTime dt = DateTime. Now; Now, use the Month property to get the current month.

How to get month number from Date in c#?

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

How do you find the first and last day of the current month?

To get the first and last day of the current month, use the getFullYear() and getMonth() methods to get the current year and month and pass them to the Date() constructor to get an object representing the two dates. Copied! const now = new Date(); const firstDay = new Date(now.


2 Answers

string sMonth = DateTime.Now.ToString("MM"); 
like image 167
Shai Avatar answered Oct 03 '22 08:10

Shai


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"); 
like image 26
Oded Avatar answered Oct 03 '22 06:10

Oded