get Previous Month - Java java.util

Java examples for java.util:Month

Description

get Previous Month

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(getPreviousMonth(date));
    }//  w ww  . j av a2s  .  com

    public static Date getPreviousMonth(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.getTime();
    }
}

Related Tutorials