akd
akd

Reputation: 6758

Is there a method to get last month name and year in C#

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

Answers (4)

Prasad
Prasad

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

user1400995
user1400995

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

Dennis Traub
Dennis Traub

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

Darren
Darren

Reputation: 70728

Why not use DateTime.AddMonths

For example:

var lastMonth = DateTime.Now.AddMonths(-1).ToString("Y");`

Upvotes: 16

Related Questions