get Last Day Of Quarter - Java java.util

Java examples for java.util:Quarter

Description

get Last Day Of Quarter

Demo Code


import java.text.SimpleDateFormat;
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(getLastDayOfQuarter(date));
    }//  www  .  ja va  2s . co  m
    
    private static SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
    
    public static String getLastDayOfQuarter(Date date) {
        int quarter = CalendarUtil.whichQuarter(date);

        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.MONTH, quarter + 2);
        int maximum = cal.getMaximum(Calendar.DAY_OF_MONTH);
        System.err.println(cal);
        cal.set(Calendar.DAY_OF_MONTH, maximum);
        System.err.println(maximum);
        date = cal.getTime();
        return sf.format(date);
    }
    
    public static int whichQuarter(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int month = cal.get(Calendar.MONTH);
        int quarter = 0;
        switch (month) {
        case 0:
        case 1:
        case 2:
            quarter = 0;
            break;
        case 3:
        case 4:
        case 5:
            quarter = 3;
            break;
        case 6:
        case 7:
        case 8:
            quarter = 6;
            break;
        case 9:
        case 10:
        case 11:
            quarter = 9;
            break;
        }
        return quarter;
    }
}

Related Tutorials