get Previous Month Index - Java java.util

Java examples for java.util:Month

Description

get Previous Month Index

Demo Code


//package com.java2s;

import java.util.Calendar;

import java.util.Date;

public class Main {
    public static void main(String[] argv) throws Exception {
        Date date = new Date();
        System.out.println(getPreviousMonthIndex(date));
    }/*  w w w  .  jav a  2 s .  c  o m*/

    public static int getPreviousMonthIndex(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

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

        return calendar.get(Calendar.MONTH);
    }
}

Related Tutorials