get Preceding Date - Java java.util

Java examples for java.util:Date Compare

Description

get Preceding Date

Demo Code

/*//from w  w w  .j av a  2s .c om
 * Copyright 2009 Yodlee, Inc.  All Rights Reserved.  Your use of this code 
 * requires a license from Yodlee.  Any such license to this code is 
 * restricted to evaluation/illustrative purposes only. It is not intended 
 * for use in a production environment, and Yodlee disclaims all warranties 
 * and/or support obligations concerning this code, regardless of the terms 
 * of any other agreements between Yodlee and you."
 */
//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(getPreceedingDate(date));
    }

    public static Date getPreceedingDate(Date date) {

        Calendar calendar = createCalendar(date.getTime());
        decrementOneDay(calendar);

        return calendar.getTime();
    }

    public static Calendar createCalendar(long timeInMillis) {

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(timeInMillis);
        calendar.setMinimalDaysInFirstWeek(calculateMinimalDaysInFirstWeek(calendar));
        return calendar;
    }

    public static void decrementOneDay(Calendar calendar) {

        int monthBeforeDecrement = calendar.get(Calendar.MONTH);
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        int monthAfterDecrement = calendar.get(Calendar.MONTH);

        // if year changes setMinimalDaysInFirstWeek for New Year
        if (monthBeforeDecrement == Calendar.JANUARY
                && monthAfterDecrement == Calendar.DECEMBER) {
            calendar.setMinimalDaysInFirstWeek(calculateMinimalDaysInFirstWeek(calendar));
        }
    }

    public static int calculateMinimalDaysInFirstWeek(Calendar calendar) {

        Calendar temp = (Calendar) calendar.clone();
        temp.set(Calendar.DAY_OF_YEAR, 1);
        int firstDayOfJan = temp.get(Calendar.DAY_OF_WEEK);
        return 8 - firstDayOfJan;
    }
}

Related Tutorials