Click here to Skip to main content
15,894,343 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
hello

i want to just retrive the last month number in c# i have try but i will get only current month.

What I have tried:

string MonthNumber = DateTime.Now.Month.ToString();
i have used above code it will give me current month number i want last months number
also tried this DateTime month = DateTime.Now.AddMonths(-1);
but it will give me hole date i just want the month number
Posted
Updated 28-Sep-16 10:35am
Comments
Philippe Mori 28-Sep-16 18:52pm    
Press F1 in Visual Studio while the caret in on DateTime and read the documentation! And even simpler, just let IntelliSense show you available properties.

Try:
C#
int lastMonth = DateTime.Now.AddMonths(-1).Month;
 
Share this answer
 
You need to get the Month Property as AddMonths(-1) will return a new DateTime instance, do it like:

C#
DateTime LastMonth = DateTime.Now.AddMonths(-1);
Console.WriteLine(LastMonth.Month);
 
Share this answer
 
v3
Comments
Karthik_Mahalingam 28-Sep-16 9:25am    
5
Try-
C#
string MonthNumber = DateTime.Now.AddMonths(-1).Month.ToString(); 

Hope, it helps :)
 
Share this answer
 
Another way to do it with a test:
C#
int MonthNumber = DateTime.Now.Month-1;
if (MonthNumber == 0)
    MonthNumber = 12; 


Another way to do it without test:
C#
int MonthNumber = ((DateTime.Now.Month+10)%12)+1;

Principle
Months are from 1 (January) to 12 (December).
Previous month of January is December
There is a mathematical function called modulus, but it is zero based (from 0 to 11) and it don't like negative values.
Fortunately month-1 is the same as month+11
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900