none
how to get previous month from current date

    Question

  •  

    Hi All,

             I am using VS03 + C#. Suppose i have date like 1/1/2000. I want to get month number of previous month means i want here to get 12 as month.

    The code in c# is appriciated.

     

    Thanks in advance.

     

    Thursday, July 31, 2008 6:55 AM

Answers

  • Well, I'm using VS2005 (Framework 2.0) but I believe that DateTime class exists in Framework 1.1 also.

    Code Snippet

    DateTime dt = new DateTime(2000, 1, 1);
    int prevMonth = dt.AddMonths(-1).Month;



    hth,
    Lior.
    Thursday, July 31, 2008 7:27 AM

All replies

  • Well, I'm using VS2005 (Framework 2.0) but I believe that DateTime class exists in Framework 1.1 also.

    Code Snippet

    DateTime dt = new DateTime(2000, 1, 1);
    int prevMonth = dt.AddMonths(-1).Month;



    hth,
    Lior.
    Thursday, July 31, 2008 7:27 AM
  •  san7481 wrote:

     

    Hi All,

             I am using VS03 + C#. Suppose i have date like 1/1/2000. I want to get month number of previous month means i want here to get 12 as month.

    The code in c# is appriciated.

     

    Thanks in advance.

     

    Hi!

    I've presumed that the date is in string format, because you didn't specified what format is it in. The code:

    Code Snippet

    string date = "1/1/2000";
    int lastMonth = 0;

    string[] splitedDate = date.Split(new Char[] {'/'});

    if (int.tryParse(splitedDate[1]))

     if (int.Parse(splitedDate[1])<=12 && int.Parse(splitedDate[1])>1)
       lastMonth = int.Parse(splitedDate[1])-1;
            if (int.Parse(splitedDate[1])==1)
      lastMonth = 12;
     if (!(int.Parse(splitedDate[1])<=12 && int.Parse(splitedDate[1])>=1))
      // show error message -> Month not between 1-12
    }
    else
     // show error message -> Month not a number

     

     

    Didn't tested it, but the logic is ok... and I think it works Smile

     

    Regards,

     

    Thursday, July 31, 2008 7:31 AM