时间工具

此工具主要是为方便时间上的计算以及时间格式传换等需求

import org.apache.commons.lang3.time.DateUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeFieldType;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 时间,日期操作
 */
public class TimeHelper {
    public final static String DATE_FORMAT_YEAR_MONTH_1 = "yyyy.MM";
    public final static String DATE_FORMAT_YEAR_MONTH_2 = "yyyy-MM";

    public final static String DATA_FORMAT_YEAR_MONTH_DAY_1 = "yyyy-MM-dd";
    public final static String DATA_FORMAT_YEAR_MONTH_DAY_2 = "yyyy.MM.dd";

    public final static String DATA_FORMAT_YEAR_MONTH_DAY_3 = "yyyy年MM月dd日";
    public final static String DATA_FORMAT_YEAR_MONTH_DAY_4 = "yyyy年MM月";

    public final static String DATE_TIME_FORMAT_DEFAULT_1 = "yyyy.MM.dd HH:mm:ss";
    public final static String DATE_TIME_FORMAT_DEFAULT_2 = "yyyy-MM-dd HH:mm:ss";
    public final static String DATE_TIME_FORMAT_DEFAULT_3 = "yyyyMMddHHmmss";
    public final static String DATE_TIME_FORMAT_DEFAULT_4 = "yyyyMMdd";
    public final static String DATE_TIME_FORMAT_DEFAULT_5 = "yyyyMM";
    public final static String DATE_TIME_FORMAT_DEFAULT_6 = "MM-dd HH:mm";
    public final static String DATE_TIME_FORMAT_DEFAULT_7 = "yyyy-MM-dd HH:mm";

    public static Date getDateByYear(int year) {
        DateTime dt = new DateTime(year, 1, 1, 0, 0, 0, 0);
        return dt.toDate();
    }

    public static Date getDateByYear(String year) {
        DateTime dt = new DateTime(Integer.parseInt(year), 1, 1, 0, 0, 0, 0);
        return dt.toDate();
    }

    public static Date addYear(Date date, int addNum) {
        DateTime dt = new DateTime(date.getTime()).plusYears(addNum);
        return dt.toDate();
    }

    public static Date getDateByMonth(int year, int month) {
        DateTime dt = new DateTime(year, month, 1, 0, 0, 0, 0);
        return dt.toDate();
    }

    public static Date getDateByMonth(String year, String month) {
        DateTime dt = new DateTime(Integer.parseInt(year), Integer.parseInt(month), 1, 0, 0, 0, 0);
        return dt.toDate();
    }

    public static Date addMonth(Date date, int addNum) {
        DateTime dt = new DateTime(date.getTime()).plusMonths(addNum);
        return dt.toDate();
    }

    public static Date addHour(Date date, int addNum){
        DateTime dt = new DateTime(date.getTime()).plusHours(addNum);
        return dt.toDate();
    }

    public static Date addSeconds(Date date, int addNum){
        DateTime dt = new DateTime(date.getTime()).plusSeconds(addNum);
        return dt.toDate();
    }

    /**
     * 获取指定日期所在天的最后一秒的时间 比如1013-11-14 23:59:59
     */
    public static Date getDateWithLastSecond(Date date) {
        DateTime dt = new DateTime(date.getTime()).withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0);
        return dt.plusDays(1).minusSeconds(1).toDate();
    }

    public static Date getDateByDate(int year, int month, int date) {
        DateTime dt = new DateTime(year, month, date, 0, 0, 0, 0);
        return dt.toDate();
    }

    public static Date getDateByDate(String year, String month, String date) {
        DateTime dt = new DateTime(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(date), 0, 0, 0, 0);
        return dt.toDate();
    }

    public static Date addDate(Date date, int addNum) {
        DateTime dt = new DateTime(date.getTime()).plusDays(addNum);
        return dt.toDate();
    }

    public static Date firstDateOfMonth(Date date) {
        DateTime dt = new DateTime(date.getTime()).withDayOfMonth(1).withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0);
        return dt.toDate();
    }

    public static Date lastDateOfMonth(Date date) {
        DateTime dt = new DateTime(date.getTime()).withDayOfMonth(1).withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0).plusMonths(1).minusMillis(1);
        return dt.toDate();
    }

    public static Date firstTimeOfDay(Date date) {
        DateTime dt = new DateTime(date.getTime()).withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0);
        return dt.toDate();
    }

    public static Date lastDateOfDay(Date date) {
        DateTime dt = new DateTime(firstTimeOfDay(addDate(date, 1))).minus(1);
        return dt.toDate();
    }

    public static boolean isInMonth(Date baseDate, Date compareDate) {
        Date startTime = firstDateOfMonth(baseDate);
        Date endTime = addMonth(startTime, 1);
        return isInTimeZone(startTime, endTime, compareDate);
    }

    public static boolean isInTimeZone(Date startTime, Date endTime, Date compareDate) {
        return startTime.getTime() <= compareDate.getTime() && endTime.getTime() > compareDate.getTime();
    }

    public static Date getDate(String date, String pattern) {
        try {
            return DateUtils.parseDate(date, new String[]{pattern});
        } catch (ParseException e) {
            DevLog.warn(TimeHelper.class, "", e);
        }

        return null;
    }

    public static String formatDate(Date date, String template) {
        if (date == null) {
            return "";
        }
        return new DateTime(date).toString(template);
    }

    public static Integer formatIntDate(Date date, String template) {
        if (date == null) {
            return 0;
        }
        return Integer.parseInt(new DateTime(date).toString(template));
    }

    public static int getDateYear(Date date){
        DateTime dateTime = new DateTime(date);
        return dateTime.get(DateTimeFieldType.year());
    }

    public static int getDateMonth(Date date){
        DateTime dateTime = new DateTime(date);
        return dateTime.get(DateTimeFieldType.monthOfYear());
    }

    public static int getDateDay(Date date){
        DateTime dateTime = new DateTime(date);
        return dateTime.get(DateTimeFieldType.dayOfMonth());
    }
    /**
     *  按天比较(不比较时分秒)
     */
    public static int compareByDay(Date time1, Date time2){
        DateTime jodaTime1 = new DateTime(time1).withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0);
        DateTime jodaTime2 = new DateTime(time2).withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0);

        return jodaTime1.compareTo(jodaTime2);
    }

    /**
     * 获取当前时间星期一的时间
     *
     * @param date
     * @return
     */
    public static Date firstDayOfWeek(Date date) {
        DateTime dateTime = new DateTime(date);
        return addDate(date, 1 - dateTime.getDayOfWeek());
    }

    public static boolean isDate(String date,String pattern){
        try{
            getDate(date,pattern);
            return  true;
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 当天时间内   从当天的 0时0分0秒  到 23时59分59秒
     * @return
     */
    public static Map<String ,Object> now(){
        Date d = new Date();
        Date frist = TimeHelper.firstTimeOfDay(d);
        Date last = TimeHelper.firstTimeOfDay(TimeHelper.addDate(d,1));
        Map<String , Object> map = new HashMap<>();
        map.put("frist",frist);
        map.put("last",last);
        return map;
    }


    /**
     * 计算两个日期相差多少天
     * @param smallDate
     * @param bigDate
     * @return
     */
    public static Integer surplusDays(Date smallDate,Date bigDate){
        try{
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            smallDate =sdf.parse(sdf.format(smallDate));
            bigDate =sdf.parse(sdf.format(bigDate));
            Calendar cal = Calendar.getInstance();
            cal.setTime(smallDate);
            long time1 = cal.getTimeInMillis();
            cal.setTime(bigDate);
            long time2 = cal.getTimeInMillis();
            long between_days=(time2-time1)/(1000*3600*24);
            return Integer.parseInt(String.valueOf(between_days));
        }catch (Exception e){
            DevLog.error(TimeHelper.class,"[surplusDays] exception",e);
            return -1;
        }
    }


    /**
     * 当前时间是否在23点至01点
     * @return
     */
    public static boolean limit_23_01(){
        SimpleDateFormat sdf = new SimpleDateFormat("HH");
        Integer hour =  Integer.parseInt(sdf.format(new Date()));
        if(hour <= 1 || hour >=23){
            return true;
        }
        return false;
    }

    /**
     * 当天起止日期
     * @return
     */
    public static Map<String ,Object> today(){
        Date startTime = TimeHelper.firstTimeOfDay(new Date());
        Date endTime = TimeHelper.firstTimeOfDay(TimeHelper.addDate(startTime,1));
        Map<String , Object> map = new HashMap<>();
        map.put("startTime",startTime);
        map.put("endTime",endTime);
        return map;
    }


    /**
     * 昨天起止日期
     * @return
     */
    public static Map<String ,Object> yesterday(){
        Date endTime = TimeHelper.firstTimeOfDay(new Date());
        Date startTime = TimeHelper.addDate(endTime, -1);
        Map<String,Object> map = new HashMap<>();
        map.put("startTime",startTime);
        map.put("endTime",endTime);
        return map;
    }

    /**
     * 前N个月
     * @return
     */
    public static List<Integer> beforMonth(int month){
        List<Integer> months = new ArrayList<>();
        if(month < 1){
            return months;
        }

        Date curTime = new Date();
        int curMonth = TimeHelper.getDateMonth(curTime);
        months.add(curMonth);

        int index = month - 1;
        for(int i = 1 ; i <= index ; i++){
            Date thatTime = TimeHelper.addMonth(curTime,-1);
            int thatMonth = TimeHelper.getDateMonth(thatTime);
            curTime = thatTime;
            months.add(thatMonth);
        }
        return months;
    }


    /**
     * 前N个月
     * @return
     */
    public static List<Integer> beforYearMonth(int month){
        List<Integer> yearMonthList = new ArrayList<>();
        if(month < 1){
            return yearMonthList;
        }

        Date curTime = new Date();
        int curYear = TimeHelper.getDateYear(curTime);
        int curMonth = TimeHelper.getDateMonth(curTime);
        int curYearMonth = Integer.parseInt(String.format("%s%s",curYear,curMonth<10?"0"+curMonth:curMonth));
        yearMonthList.add(curYearMonth);

        int index = month - 1;
        for(int i = 1 ; i <= index ; i++){
            Date thatTime = TimeHelper.addMonth(curTime,-1);
            int thatMonth = TimeHelper.getDateMonth(thatTime);
            int thatYear = TimeHelper.getDateYear(thatTime);
            curTime = thatTime;
            yearMonthList.add(Integer.parseInt(String.format("%s%s",thatYear,thatMonth<10?"0"+thatMonth:thatMonth)));
        }
        return yearMonthList;
    }
}

猜你喜欢

转载自www.cnblogs.com/codigup/p/10114599.html