com.webarch.common.datetime.DateTimeUtils.java Source code

Java tutorial

Introduction

Here is the source code for com.webarch.common.datetime.DateTimeUtils.java

Source

/*
    Copyright  DR.YangLong
    
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
    
    http://www.apache.org/licenses/LICENSE-2.0
    
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/
package com.webarch.common.datetime;

import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.joda.time.Period;
import org.joda.time.PeriodType;

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

/**
 * functional describe:???
 *
 * @author DR.YangLong [410357434@163.com]
 * @version 1.0 2015/5/13 9:24
 */
public class DateTimeUtils {
    /**
     * ??
     */
    public static final int YEAR_UNIT = 0;
    public static final int MONTH_UNIT = 1;
    public static final int DAY_UNIT = 2;
    public static final int HOURE_UNIT = 3;
    public static final int MINUTE_UNIT = 4;

    private DateTimeUtils() {
    }

    public static Date getFirstDayOfWeek(Date date) {
        DateTime dateTime = new DateTime(date);
        return dateTime.minusDays(dateTime.getDayOfWeek() - 1).toDate();
    }

    public static Date getLastDayOfWeek(Date date) {
        DateTime dateTime = new DateTime(date);
        return dateTime.plusDays(7 - dateTime.getDayOfWeek()).toDate();
    }

    /**
     * ?
     *
     * @return
     */
    public static Period getTimePeriod(Date startTime, Date endTime, PeriodType periodType) {
        if (periodType == null)
            periodType = PeriodType.minutes();
        DateTime dateTimeStart = new DateTime(startTime);
        DateTime dateTimeEnd = new DateTime(endTime);
        Period p = new Period(dateTimeStart, dateTimeEnd, periodType);
        return p;
    }

    /**
     * ?
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static long getPeriodYears(Date startTime, Date endTime) {
        return getTimePeriod(startTime, endTime, PeriodType.years()).getYears();
    }

    /**
     * ?
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static long getPeriodDays(Date startTime, Date endTime) {
        return getTimePeriod(startTime, endTime, PeriodType.days()).getDays();
    }

    /**
     * ??
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static long getPeriodHours(Date startTime, Date endTime) {
        return getTimePeriod(startTime, endTime, PeriodType.hours()).getHours();
    }

    /**
     * ?
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static long getPeriodSeconds(Date startTime, Date endTime) {
        return getTimePeriod(startTime, endTime, PeriodType.seconds()).getSeconds();
    }

    /**
     * ?
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static long getPeriodMinutes(Date startTime, Date endTime) {
        return getTimePeriod(startTime, endTime, PeriodType.minutes()).getMinutes();
    }

    /**
     * ?
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static long getPeriodMonths(Date startTime, Date endTime) {
        return getTimePeriod(startTime, endTime, PeriodType.months()).getMonths();
    }

    /**
     * ?
     *
     * @param startTime
     * @param endTime
     * @return
     */
    public static long getPeriodMillis(Date startTime, Date endTime) {
        Duration duration = new Duration(new DateTime(startTime), new DateTime(endTime));
        return duration.getMillis();
    }

    /**
     * ?
     *
     * @param date     ?
     * @param before   ??
     * @param timeUnit ??,<code>0,1,2,3,4</code>
     * @return ??
     */
    public static Date getBeforeDate(Date date, final int before, final int timeUnit) {
        DateTime dateTime = new DateTime(date);
        Date result;
        switch (timeUnit) {
        case YEAR_UNIT:
            result = dateTime.minusYears(before).toDate();
            break;
        case MONTH_UNIT:
            result = dateTime.minusMonths(before).toDate();
            break;
        case DAY_UNIT:
            result = dateTime.minusDays(before).toDate();
            break;
        case HOURE_UNIT:
            result = dateTime.minusHours(before).toDate();
            break;
        case MINUTE_UNIT:
            result = dateTime.minusMinutes(before).toDate();
            break;
        default:
            result = date;
        }
        return result;
    }

    /**
     * ?
     *
     * @param date     ?
     * @param after    ??
     * @param timeUnit ??
     * @return ??
     */
    public static Date getAfterDate(Date date, final int after, final int timeUnit) {
        DateTime dateTime = new DateTime(date);
        Date result;
        switch (timeUnit) {
        case YEAR_UNIT:
            result = dateTime.plusYears(after).toDate();
            break;
        case MONTH_UNIT:
            result = dateTime.plusMonths(after).toDate();
            break;
        case DAY_UNIT:
            result = dateTime.plusDays(after).toDate();
            break;
        case HOURE_UNIT:
            result = dateTime.plusHours(after).toDate();
            break;
        case MINUTE_UNIT:
            result = dateTime.plusMinutes(after).toDate();
            break;
        default:
            result = date;
        }
        return result;
    }

    /**
     * ?
     *
     * @return
     */
    public static Date getToday() {
        return formatDate(new Date());
    }

    /**
     * ??
     *
     * @param month ?
     * @return
     */
    public static Date getMonthFristWeekSunday(String month) {
        Calendar c = Calendar.getInstance();
        c.setTime(parse(month, "yyyy-MM"));
        c.set(Calendar.DATE, 1);
        int dayNum = c.get(Calendar.DAY_OF_WEEK);
        c.add(Calendar.DATE, 1 - dayNum);
        return c.getTime();
    }

    /**
     * ??
     *
     * @param date
     * @return
     */
    public static Date getLastDayOfMonth(Date date) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.DATE, 1);
        c.roll(Calendar.DATE, -1);

        c.setTime(date);
        c.add(Calendar.MONTH, 1);
        c.set(Calendar.DATE, 1);
        c.add(Calendar.DATE, -1);
        return c.getTime();
    }

    /**
     * ???
     *
     * @param month ?
     * @return
     */
    public static Date getMonthLastWeekSaturday(String month) {
        Calendar c = Calendar.getInstance();
        Date lastDay = getLastDayOfMonth(parse(month, "yyyy-MM"));
        c.setTime(lastDay);
        int dayNum = c.get(Calendar.DAY_OF_WEEK);
        if (dayNum != 7) {
            c.add(Calendar.DATE, 7 - dayNum);
        }
        return c.getTime();
    }

    /**
     * ?
     *
     * @return
     */
    public static Date getCurrentYearFirst() {
        Calendar today = Calendar.getInstance();
        int yearPlus = Calendar.getInstance().get(Calendar.YEAR);
        today.set(yearPlus, 1, 1);
        return new Date(today.getTimeInMillis());
    }

    /**
     * ??
     *
     * @return
     */
    public static Date getCurrentYearLast() {
        Calendar today = Calendar.getInstance();
        int yearPlus = Calendar.getInstance().get(Calendar.YEAR);
        today.set(yearPlus, 12, 31);
        return new Date(today.getTimeInMillis());
    }

    /**
     * ??
     *
     * @param startMilliSecond 
     * @return 
     */
    public static long compareToSecond(long startMilliSecond) {
        if (startMilliSecond > 0) {
            // ?
            long currentMilli = System.currentTimeMillis();
            long startSecond = startMilliSecond / 1000;
            long endSecond = currentMilli / 1000;

            return endSecond - startSecond;
        }

        return -1;
    }

    /**
     * ?
     * @return
     */
    public static String getGreetings() {
        Date curTime = new Date();
        int hour = curTime.getHours();
        String greetings = "";
        if (hour >= 0 && hour < 6) {
            greetings = "";
        } else if (hour >= 6 && hour < 8) {
            greetings = "";
        } else if (hour >= 8 && hour < 11) {
            greetings = "?";
        } else if (hour >= 11 && hour < 14) {
            greetings = "?";
        } else if (hour >= 14 && hour < 18) {
            greetings = "?";
        } else if (hour >= 18 && hour < 22) {
            greetings = "";
        } else if (hour >= 22 && hour < 24) {
            greetings = "?";
        }
        return greetings;
    }

    /**
     * 
     *
     * @param date 
     * @return
     */
    public static Date formatDate(Date date) {
        return parse(format(date), "yyyy-MM-dd");
    }

    /**
     * "yyyy-MM-dd"?
     *
     * @param date 
     * @return
     */
    public static String format(Date date) {
        if (date == null) {
            return "";
        }
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        return df.format(date);
    }

    /**
     * "yyyyMMdd hh:mm"?
     *
     * @param date 
     * @return
     */
    public static String formatChinese(Date date) {
        if (date == null) {
            return "";
        }
        DateFormat df = new SimpleDateFormat("yyyyMMdd HH:mm");
        return df.format(date);
    }

    /**
     * ?pattern?
     *
     * @param date 
     * @param pattern ??
     * @return
     */
    public static String format(Date date, String pattern) {
        if (date == null) {
            return "";
        }
        DateFormat df = new SimpleDateFormat(pattern);
        return df.format(date);
    }

    /**
     * "yyyy-MM-dd HH:mm"??
     *
     * @param dateString
     * @return
     */
    public static Date parse(String dateString) {
        return parse(dateString, "yyyy-MM-dd HH:mm:ss");
    }

    /**
     * pattern??
     *
     * @param dateString
     * @param pattern
     * @return
     */
    public static Date parse(String dateString, String pattern) {
        DateFormat df = new SimpleDateFormat(pattern);
        Date date = null;
        try {
            date = df.parse(dateString);
        } catch (Throwable t) {
            date = null;
        }
        return date;
    }
}