All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.ultreia.java4all.util.Dates Maven / Gradle / Ivy

There is a newer version: 1.2.1
Show newest version
package io.ultreia.java4all.util;

/*-
 * #%L
 * Java Util extends by Ultreia.io
 * %%
 * Copyright (C) 2018 Ultreia.io
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Lesser Public License for more details.
 * 
 * You should have received a copy of the GNU General Lesser Public
 * License along with this program.  If not, see
 * .
 * #L%
 */

import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * Created by tchemit on 29/12/2017.
 *
 * @author Tony Chemit - [email protected]
 */
public final class Dates {

    public static final String DEFAULT_PATTERN = "dd/MM/yyyy";

    public static final String MONTH_PATTERN = "MM/yyyy";

    /**
     * Format a date using the pattern in argument. The pattern is the same using
     * for DateFormat object.
     *
     * @param date    the date to format
     * @param pattern the pattern to use
     * @return a String corresponding to the date formatted
     * @see DateFormat
     */
    public static String formatDate(Date date, String pattern) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        return simpleDateFormat.format(date);
    }

    public static String formatDate(Date date, String pattern, Locale locale) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern, locale);
        return simpleDateFormat.format(date);
    }

    /**
     * Parse a date using the pattern in argument. The pattern is the same using
     * for DateFormat object.
     *
     * @param date    the String to parse
     * @param pattern the pattern to use
     * @return a Date corresponding to the String argument parsed
     * @throws ParseException for parsing errors
     * @see DateFormat
     */
    public static Date parseDate(String date, String pattern) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        Date result = simpleDateFormat.parse(date);
        return result;
    }

    /**
     * Create a new date from day, month and year (French version).
     * The month is the real month of the year and not the one which is stored
     * in Calendar object.
     *
     * @param s  value of the seconds 1-60
     * @param m  value of the minutes 1-60
     * @param h  value of the hours 1-24
     * @param dd value of the day 1-31
     * @param mm value of the month 1-12
     * @param yy value of the year 0-9999
     * @return a new date
     */
    public static Date createDate(int s, int m, int h, int dd, int mm, int yy) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(0L);
        calendar.set(Calendar.YEAR, yy);
        calendar.set(Calendar.MONTH, mm - 1);
        calendar.set(Calendar.DAY_OF_MONTH, dd);
        calendar.set(Calendar.HOUR_OF_DAY, h);
        calendar.set(Calendar.MINUTE, m);
        calendar.set(Calendar.SECOND, s);
        return calendar.getTime();
    }

    /**
     * Create a new date from day, month and year (French version).
     * The month is the real month of the year and not the one which is stored
     * in Calendar object. Time is set to 00:00:00.000
     *
     * @param dd value of the day 1-31
     * @param mm value of the month 1-12
     * @param yy value of the year 0-9999
     * @return a new date
     */
    public static Date createDate(int dd, int mm, int yy) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, yy);
        calendar.set(Calendar.MONTH, mm - 1);
        calendar.set(Calendar.DAY_OF_MONTH, dd);
        return setMinTimeOfDay(calendar.getTime());
    }

    /**
     * Create a new date after the current date (today) with modification on day, month and year.
     * You can use negative values on arguments to have a date before today.
     *
     * @param ddStep nb days you want to increase from the current date
     * @param mmStep nb months you want to increase from the current date
     * @param yyStep nb years you want to increase from the current date
     * @return a new date from the current date increase by days, months and years.
     */
    public static Date createDateAfterToday(int ddStep, int mmStep, int yyStep) {
        Calendar calendar = getDefaultCalendar(new Date());
        calendar.add(Calendar.DAY_OF_MONTH, ddStep);
        calendar.add(Calendar.MONTH, mmStep);
        calendar.add(Calendar.YEAR, yyStep);
        return calendar.getTime();
    }

    /**
     * Set the last day of month to the date in argument.
     * The value depends on the month of the date. (30 april, 28 february, ...)
     *
     * @param date Date to modify
     * @return the date with day of month modified
     */
    public static Date setLastDayOfMonth(Date date) {
        Calendar calendar = getDefaultCalendar(date);
        int maximum = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        calendar.set(Calendar.DAY_OF_MONTH, maximum);
        Date lastDay = calendar.getTime();
        return lastDay;
    }

    /**
     * Set the first day of month to the date in argument.
     *
     * @param date Date to modify
     * @return the date with day of month modified
     */
    public static Date setFirstDayOfMonth(Date date) {
        Calendar calendar = getDefaultCalendar(date);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        Date firstDay = calendar.getTime();
        return firstDay;
    }

    /**
     * Set the last day of year to the date in argument.
     *
     * @param date Date to modify
     * @return the date with day of year modified
     */
    public static Date setLastDayOfYear(Date date) {
        Calendar calendar = getDefaultCalendar(date);
        int maximum = calendar.getActualMaximum(Calendar.DAY_OF_YEAR);
        calendar.set(Calendar.DAY_OF_YEAR, maximum);
        Date lastDay = calendar.getTime();
        return lastDay;
    }

    /**
     * Set the first day of year to the date in argument.
     *
     * @param date Date to modify
     * @return the date with day of year modified
     */
    public static Date setFirstDayOfYear(Date date) {
        Calendar calendar = getDefaultCalendar(date);
        calendar.set(Calendar.DAY_OF_YEAR, 1);
        Date firstDay = calendar.getTime();
        return firstDay;
    }

    /**
     * Set the min time of the day : 00:00:00.000.
     *
     * @param date to modify
     * @return Date with the time set to the minimum in the day
     */
    public static Date setMinTimeOfDay(Date date) {
        Calendar calendar = getDefaultCalendar(date);
        calendar.set(Calendar.AM_PM, Calendar.AM);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * Set the max time of the day. EUROPE : 23:59:59.999.
     *
     * @param date to modify
     * @return Date with the time set to the maximum in the day
     */
    public static Date setMaxTimeOfDay(Date date) {
        Calendar calendar = getDefaultCalendar(date);
        calendar.set(Calendar.AM_PM, Calendar.PM);
        calendar.set(Calendar.HOUR, 11);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTime();
    }

    /**
     * Check if the first date in argument is included between the two other
     * dates. The argument myDate can be equals to beforeDate or afterDate to
     * validate the includes.
     *
     * @param myDate     the date to test
     * @param beforeDate the first date of the period to test
     * @param afterDate  the second date of the period to test
     * @return true if myDate is included between beforeDate and afterDate
     */
    public static boolean between(Date myDate, Date beforeDate, Date afterDate) {
        if (myDate == null) {
            return false;
        }
        boolean result = true;
        result &= myDate.after(beforeDate) || myDate.compareTo(beforeDate) == 0;
        result &= afterDate == null || myDate.before(afterDate) ||
                myDate.compareTo(afterDate) == 0;
        return result;
    }

    /**
     * Check if the current date is between the two dates in argument.
     *
     * @param beforeDate the first date of the period
     * @param afterDate  the second date of the period
     * @return true if the current date is included between the two dates,
     * false otherwise
     * @see #between(Date, Date, Date)
     */
    public static boolean currentPeriod(Date beforeDate, Date afterDate) {
        return between(new Date(), beforeDate, afterDate);
    }

    /**
     * Get the month value from a date (between 0 and 11).
     *
     * @param date the date to extract month
     * @return the month value of the date
     */
    public static int getMonth(Date date) {
        Calendar calendar = getDefaultCalendar(date);
        return calendar.get(Calendar.MONTH);
    }

    /**
     * Do the difference between the two dates in argument. The result is a number
     * of seconds between the two dates.
     *
     * @param beginDate first date
     * @param endDate   second date
     * @return a number of seconds between beginDate and endDate
     */
    public static int getDifferenceInSeconds(Date beginDate, Date endDate) {
        long begin = beginDate.getTime();
        long end = endDate.getTime();
        return (int) Math.ceil((end - begin) / 1000);
    }

    /**
     * Do the difference between the two dates in argument. The result is a number
     * of minutes between the two dates.
     *
     * @param beginDate first date
     * @param endDate   second date
     * @return a number of minutes between beginDate and endDate
     */
    public static int getDifferenceInMinutes(Date beginDate, Date endDate) {
        long begin = beginDate.getTime();
        long end = endDate.getTime();
        // 60000 = 60 * 1000
        return (int) Math.ceil((end - begin) / 60000);
    }

    /**
     * Do the difference between the two dates in argument. The result is a number
     * of hours between the two dates.
     *
     * @param beginDate first date
     * @param endDate   second date
     * @return a number of hours between beginDate and endDate
     */
    public static int getDifferenceInHours(Date beginDate, Date endDate) {
        long begin = beginDate.getTime();
        long end = endDate.getTime();
        // 3600000 = 60 * 60 * 1000
        return (int) Math.ceil((end - begin) / 3600000);
    }

    /**
     * Do the difference between the two dates in argument. The result is a number
     * of days between the two dates.
     * Ex : 28/01/2009 and 08/02/2009 return 11.
     *
     * @param beginDate first date
     * @param endDate   second date
     * @return a number of days between beginDate and endDate
     */
    public static int getDifferenceInDays(Date beginDate, Date endDate) {
        long begin = beginDate.getTime();
        long end = endDate.getTime();
        // 86400000 = 24 * 60 * 60 * 1000
        return (int) Math.ceil((end - begin) / 86400000);
    }

    /**
     * Do the difference between the two dates in argument. The result is a number
     * of months between the two dates.
     * Ex : 01/01/2009 and 28/02/2009 return 2 months.
     * Warning, if beginDate is inferior to endDate, the result will be 1 minimum
     *
     * @param beginDate first date
     * @param endDate   second date
     * @return a number of months between beginDate and endDate
     */
    public static int getDifferenceInMonths(Date beginDate, Date endDate) {
        int count = 0;
        Calendar fromCalendar = getDefaultCalendar(beginDate);
        Calendar thruCalendar = getDefaultCalendar(endDate);

        while (fromCalendar.before(thruCalendar)) {
            fromCalendar.add(Calendar.MONTH, 1);
            count++;
        }
        return count;
    }

    /**
     * Get the age of a person born on the date in argument. The result is a number
     * of years between the birth date and now.
     * Ex : 01/01/2000 returns 11 years (now date is 26/10/2011).
     *
     * @param birthDate birth date
     * @return a number of years between birthDate and now
     */
    public static int getAge(Date birthDate) {
        int count = 0;
        Calendar fromCalendar = getDefaultCalendar(birthDate);
        Calendar thruCalendar = getDefaultCalendar(new Date());

        fromCalendar.add(Calendar.YEAR, 1);
        while (fromCalendar.before(thruCalendar)) {
            count++;
            fromCalendar.add(Calendar.YEAR, 1);
        }
        return count;
    }

    /**
     * Get libelle of the month corresponding to the number given in argument.
     *
     * @param monthNumber between 1-12
     * @param locale      Locale for language support
     * @return a String corresponding to the libelle of the month
     */
    public static String getMonthLibelle(int monthNumber, Locale locale) {
        return new DateFormatSymbols(locale).getMonths()[monthNumber - 1];
    }

    /**
     * Get libelle of the month corresponding to the number given in argument.
     *
     * @param monthNumber between 1-12
     * @return a String corresponding to the libelle of the month
     */
    public static String getMonthLibelle(int monthNumber) {
        return getMonthLibelle(monthNumber, Locale.getDefault());
    }

    /**
     * Get the date before today
     *
     * @param date concerned
     * @return Date before today
     */
    public static Date getYesterday(Date date) {
        Calendar cal = getDefaultCalendar(date);
        if (cal.get(Calendar.MONTH) == Calendar.JANUARY && cal.get(Calendar.DAY_OF_MONTH) == 1) {
            cal.roll(Calendar.YEAR, false);
        }
        if (cal.get(Calendar.DAY_OF_MONTH) == 1) {
            cal.roll(Calendar.MONTH, false);
        }
        cal.roll(Calendar.DAY_OF_MONTH, false);
        return cal.getTime();
    }

    /**
     * Get the calendar corresponding to the {@code date}. The default calendar
     * will be returned (default time zone and locale).
     *
     * @param date used to set the calendar time
     * @return the default calendar with time corresponding to the {@code date}
     */
    public static Calendar getDefaultCalendar(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar;
    }

    /**
     * Truncate a date to its week (to monday). It's equivalent to a call to
     * {@code org.apache.commons.lang3.time.DateUtils#truncate(Date, int)}
     * and giving {@link Calendar#DAY_OF_WEEK} argument, but such a call
     * raise an exception showing that this field is not supported. This method
     * allows you to bypass this limitation.
     *
     * @param date any date
     * @return a date in the same week as given date, a monday. All field below
     * (hours, secondes, ms) are zeroed.
     */
    public static Date truncateToDayOfWeek(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }


    /**
     * Enleve les données des heures (hour, minute, second, milli = 0).
     *
     * @param date la date a modifier
     * @return la date d'un jour
     */
    public static Date getDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        date = calendar.getTime();
        return date;
    }

    /**
     * Positionne une date sur la fin d'un jour
     *
     * @param date la date a modifier
     * @return la date d'un jour
     */
    public static Date getEndOfDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MILLISECOND, 999);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        date = calendar.getTime();
        return date;
    }

    /**
     * Créer la date qui utilise le jour donné dans {@code day} et l'heure
     * donnée dans {@code time}.
     *
     * @param day           le jour à utiliser
     * @param time          l'heure a utiliser
     * @param useSecond     FIXME
     * @param useMiliSecond FIXME
     * @return la date donnée avec l'heure courante
     */
    public static Date getDateAndTime(Date day, Date time, boolean useSecond, boolean useMiliSecond) {

        Calendar calendar = Calendar.getInstance();

        // recuperation de l'heure
        calendar.setTime(time);
        int h = calendar.get(Calendar.HOUR_OF_DAY);
        int m = calendar.get(Calendar.MINUTE);
        int s = useSecond ? calendar.get(Calendar.SECOND) : 0;
        int ms = useMiliSecond ? calendar.get(Calendar.MILLISECOND) : 0;

        calendar.setTime(day);

        // appliquer l'heure
        calendar.set(Calendar.HOUR_OF_DAY, h);
        calendar.set(Calendar.MINUTE, m);
        calendar.set(Calendar.SECOND, s);
        calendar.set(Calendar.MILLISECOND, ms);

        return calendar.getTime();

    }

    /**
     * Créer la date qui utilise uniquement l'heure
     * donnée dans {@code dayTime}.
     *
     * @param dayTime       l'heure a utiliser
     * @param useSecond     FIXME
     * @param useMiliSecond FIXME
     * @return la date donnée avec uniquement l'heure courante
     */
    public static Date getTime(Date dayTime, boolean useSecond, boolean useMiliSecond) {
        Calendar calendar = Calendar.getInstance();

        // recuperation de l'heure
        calendar.setTime(dayTime);
        int h = calendar.get(Calendar.HOUR_OF_DAY);
        int m = calendar.get(Calendar.MINUTE);
        int s = calendar.get(Calendar.SECOND);
        int ms = calendar.get(Calendar.MILLISECOND);


        // on part d'une date vide
        calendar.setTimeInMillis(0);

        // appliquer l'heure
        calendar.set(Calendar.HOUR_OF_DAY, h);
        calendar.set(Calendar.MINUTE, m);
        if (useSecond) {
            calendar.set(Calendar.SECOND, s);
        }
        if (useMiliSecond) {
            calendar.set(Calendar.MILLISECOND, ms);
        }

        return calendar.getTime();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy