Reputation: 6758
DateTime.Now.ToString("Y")
returns me : August 2013
Is there an easy method to get last month in the same format?
Something like : DateTime.LastMonth.ToString("Y")
and output will be : July 2013
I know this method doesnt exists :) but maybe there is something else to achieve that output? Or I will need to create my own method for that?
Upvotes: 5
Views: 11884
Reputation: 1
If you want to get abbreviated month name, you can below lines,
DateTime lastMonth = DateTime.Now.AddMonths(-1);
string Month = CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(lastMonth.Month) ;
Upvotes: 0
Reputation:
Use extension methods...Maybe something along the lines...
public static string LastMonth(this DateTime dt)
{
return DateTime.Now.AddMonths(-1).ToString("Y");
}
Upvotes: 1
Reputation: 51634
You can add or subtract months from a given date by using DateTime.AddMonths()
var lastMonth = DateTime.Now.AddMonths(-1);
var lastMonthAsString = lastMonth.ToString("Y");
The same exists for other time intervals like AddDays()
, AddSeconds()
or AddYears()
. You can find all available methods at MSDN's DateTime documentation.
Upvotes: 9
Reputation: 70728
Why not use DateTime.AddMonths
For example:
var lastMonth = DateTime.Now.AddMonths(-1).ToString("Y");`
Upvotes: 16