How to get the Last Month from System.Date ??

Hello Everyone,

I'm using the System.DateTime curr = DateTime.Now;

this gives me todays date...As today is 22nd Feb, 2006.....From this date if we want to get last month how we get it....

I want something that can give me 1/1/2006 -- 1/31/2006 (mm/dd/yyyy)

Secondly, how can I say get this month or this quarter..

Say this month -- 2/1/2006 -- 2/28/2006 (mm/dd/yyyy)

This Quarter -- 1/1/2006 -- 3/31/2006 (mm/dd/yyyy)

If you can give me some code snippet how to do it....

Thanks,

Harsimrat



Answer this question

How to get the Last Month from System.Date ??

  • An_Cala

    DateTime is a class, not a method. As such, it HAS methods.

    DateTime dt2 = new DateTime(dt.Year, (dt.Month == 1) 12 : dt.Month-1, 1);

    will give you a date time of the first day in the month before the month in dt, for example.

    DateTime dtStart = new DateTime(dt.Year, Math.Ceil(dt.Month/3.0), 1);

    is a first guess at how to get the first day of a quarter.



  • Wodin

    You can create a new date using the current month - 1. The month property is a number, so you can easily use that to generate quarters.



  • AddinDeveloper

    Hello Christian,

    the only method I can find other that DateTime is

    MonthCalendar curr1 = new MonthCalendar();

    from here how can I subtract 1 and get the last month or this quarter...

    Thanks,

    Harsimrat


  • DerekLakin

    Sorry for asking the same thing again and again..

    DateTime lastday = DateTime.LastDayInMonth;

    Error 1 'System.DateTime' does not contain a definition for 'LastDayInMonth'


  • Pramod Gurunath - MSFT

    Sorry, it's

    DateTime.DaysInMonth

    and it takes a year and a month and returns a digit.



  • Antonionini

    DateTime.LastDayInMonth

    It's a static method so you won't see it on a class instance.



  • Alan Cameron Wills

    Thanks a lot.....
  • Gordon Donald

    Hello,

    DateTime curr = DateTime.Now;

    curr = curr.AddMonths(-1);

    double curr1 = curr.Day;

    curr1 = curr1 - 1;

    curr = curr.AddDays(-curr1);

    But then I got stuck here, curr gives me 1/1/2006 but then how can I say without comparing or by doing if else ...its Jan and add 30 days to it to get 1/31/2006.

    Or if its Feb - 2/1/2006 -- 2/28/2006

    or some other Month.....


  • How to get the Last Month from System.Date ??