4

I'm trying to get 1 month ago date and time but what i get from this was 2013 11 02 which the correct one should be 2013 12 02 pls help.

My Code as below :-

Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.MONTH, -1);

    int thisYear = calendar.get(Calendar.YEAR);
    int thisMonth = calendar.get(Calendar.MONTH);
    int thisDay = calendar.get(Calendar.DAY_OF_MONTH);
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
micky
  • 235
  • 2
  • 4
  • 16

2 Answers2

14

Your code is correct, I think the months are zero indexed ;)

Try this,

Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, -1);
Date date = calendar.getTime();
SimpleDateFormat format = new SimpleDateFormat("yyyy MM dd");
String dateOutput = format.format(date);

This should interpret the date values for you in logical units rather than the internal representation

Checkout out documentation for SimpleDateFormat for a more custom approach, I just made some assumptions based on your question text.

Greg Giacovelli
  • 10,164
  • 2
  • 47
  • 64
  • Oh like you want it to print the word january? you could use a lookup table that maps Calendar.JANUARY -> "January" or just use a SimpleDateFormatter and pass it the date that the Calendar object represents – Greg Giacovelli Jan 02 '14 at 07:03
  • It should, try it, `calendar.set(Calendar.MONTH, Calendar.MARCH);` `calendar.set(Calendar.DAY_OF_MONTH, 31);` `calendar.add(Calendar.MONTH, -1);` – Greg Giacovelli Jan 02 '14 at 07:16
4

You can try this

    Calendar calendar = Calendar.getInstance();
    if(calendar.get(Calendar.MONTH) == Calendar.JANUARY){
        calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR)-1);
        calendar.set(Calendar.MONTH, calendar.DECEMBER);
    }else{
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH)-1);
    }

    int thisYear = calendar.get(Calendar.YEAR);
    int thisMonth = calendar.get(Calendar.MONTH);
    int thisDay = calendar.get(Calendar.DAY_OF_MONTH);
dinesh sharma
  • 3,312
  • 1
  • 22
  • 32
  • You can't do `calendar.YEAR-1`. This makes no sense. YEAR is a static member of the Calendar class. YEAR is a constant. To subtract 1 from it makes no sense since it is just a key to look up a value from – Greg Giacovelli Jan 02 '14 at 07:07
  • this code return result 2014-11-2 00:00:00. I should get 2013-12-02 00:00:00 – micky Jan 02 '14 at 07:09
  • I have edited this answer after running it successfully try it now – dinesh sharma Jan 02 '14 at 07:18