get Last Month Start - Java java.util

Java examples for java.util:Month

Description

get Last Month Start

Demo Code


//package com.java2s;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Main {
    public static void main(String[] argv) throws Exception {
        int year = 2;
        int month = 2;
        System.out.println(getLastMonthStart(year, month));
    }/*from  w ww .ja  v  a  2 s  . c o  m*/

    public static Date getLastMonthStart(int year, int month) {
        Calendar result = Calendar.getInstance();
        result.setTime(getMonthStart(year, month));
        result.add(Calendar.MONTH, -1);
        return result.getTime();
    }

    public static Date getMonthStart(int year, int month) {
        return parseDate(String.valueOf(year) + month, "yyyyM");
    }

    public static Date parseDate(String dateString, String format) {
        SimpleDateFormat formater = new SimpleDateFormat();
        formater.applyPattern(format);
        formater.setLenient(false);
        try {
            return formater.parse(dateString);
        } catch (ParseException e) {
            return null;
        }
    }
}

Related Tutorials