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

10,914

Solution 1

Why not use DateTime.AddMonths

For example:

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

Solution 2

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.

Share:
10,914
akd
Author by

akd

Updated on June 06, 2022

Comments

  • akd
    akd almost 2 years

    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?

  • akd
    akd over 10 years
    it doesnt seem to be a static method of DateTime?
  • akd
    akd over 10 years
    get it I shoudl use Now too :)
  • Darren
    Darren over 10 years
    @akdurmus - no problem :)
  • Robert McKee
    Robert McKee over 10 years
    Correct, it wouldn't be a static method, it works on instantiated DateTime's only, which is what DateTime.Now returns.