get Current Quarter Start Times - Java java.util

Java examples for java.util:Quarter

Description

get Current Quarter Start Times

Demo Code


//package com.java2s;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import java.util.TimeZone;

public class Main {
    public static void main(String[] argv) throws Exception {
        System.out.println(getCurrentQuarterStartTimes());
    }/*from  w w w  .  ja v  a 2 s.com*/

    private static TimeZone timeZoneChina = TimeZone
            .getTimeZone("Asia/Shanghai");

    public static Date getCurrentQuarterStartTimes() {
        SimpleDateFormat longSdf = getSimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat shortSdf = getSimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, -1); //?
        int currentMonth = c.get(Calendar.MONTH) + 1;
        Date now = null;
        try {
            if (currentMonth >= 1 && currentMonth <= 3)
                c.set(Calendar.MONTH, 0);
            else if (currentMonth >= 4 && currentMonth <= 6)
                c.set(Calendar.MONTH, 3);
            else if (currentMonth >= 7 && currentMonth <= 9)
                c.set(Calendar.MONTH, 6);
            else if (currentMonth >= 10 && currentMonth <= 12)
                c.set(Calendar.MONTH, 9);
            c.set(Calendar.DATE, 1);
            now = longSdf.parse(shortSdf.format(c.getTime()) + " 00:00:00");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;
    }

    public static SimpleDateFormat getSimpleDateFormat(String formatStr) {
        SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
        sdf.setTimeZone(timeZoneChina);
        return sdf;
    }
}

Related Tutorials