JAVA 日期工具类

贴代码!

package com.zy.game.utils;

import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author zxq
 * @description 时间工具类
 * @date 2020/9/27
 */
public class DateUtils {

    public static final String FULL_TIME_SPLIT_PATTERN = "yyyy-MM-dd HH:mm:ss";

    public static final String FULL_TIME_SPLIT__PATTERN = "yyyy-MM-dd-HH:mm:ss";

    public static final String CST_TIME_PATTERN = "EEE MMM dd HH:mm:ss zzz yyyy";

    public static final String FULL_TIME_PATTERN = "yyyyMMddHHmmss";

    public static final String FULL_DAY_SPLIT_PATTERN = "yyyy-MM-dd";

    public static final String FULL_TIME_NOT_DAY_PATTERN = "HH:mm";

    private static final String FORMAT = "yyyy-MM-dd";

    public static final String FULL_DAY_MONTH = "MM-dd";

    public static final String FULL_DAY_PATTERN = "dd";


    public static void main(String[] args) {

    }

    /**
     * @description:计算岁数
     * @param birthDay
     * @return: int
     * @author: zxq
     * @Date: 2020/9/27 14:57
     */
    public static  int getAge(Date birthDay)  {
        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDay)) { //出生日期晚于当前时间,无法计算
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);  //当前年份
        int monthNow = cal.get(Calendar.MONTH);  //当前月份
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        int age = yearNow - yearBirth;   //计算整岁数
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;//当前日期在生日之前,年龄减一
            }else{
                age--;//当前月份在生日之前,年龄减一
            } }
        return age;
    }


    /**
     * @description:计算两个时间相差天数
     * @param beginDate
     * @param endDate
     * @return: int
     * @author: zxq
     * @Date: 2020/9/27 14:47
     */
    public static int getDays(Date beginDate, Date endDate) {
        if (beginDate == null || endDate == null) {
            return 0;
        }
        long day = 0;
        try {
            endDate.setHours(10);
            endDate.setMinutes(0);
            endDate.setSeconds(0);
            double millsOfDay = 1000 * 60 * 60 * 24;
            double days = ((double) (endDate.getTime() - beginDate.getTime()) / millsOfDay);
            return (int) Math.ceil(days);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (int) day;
    }

   /**
    * @description:格式化日期
    * @param date
    * @param pattern
    * @return: java.lang.String
    * @author: zxq
    * @Date: 2020/9/27 14:44
    */
    public static String dateFormat(Date date, String pattern) {
        String str = null;
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        if (date != null) {
            str = sdf.format(date);
        }
        return str;
    }

    /**
     * @description: 时间格式转字符串
     * @param date
     * @return: java.lang.String
     * @author: zxq
     * @Date: 2020/9/27 14:43
     */
    public static String dateToString(Date date) {
        String str = null;
        SimpleDateFormat sdf = new SimpleDateFormat(FORMAT);
        if (date != null) {
            str = sdf.format(date);
        }
        return str;
    }


    /**
     * @description:比较时间,获取时间相差的文本
     * @param endDate
     * @param startDate
     * @return: java.lang.String
     * @author: zxq
     * @Date: 2020/9/27 14:42
     */
    public static String calYears(Date endDate, Date startDate) {
        try {
            Calendar c1 = Calendar.getInstance();
            Calendar c2 = Calendar.getInstance();
            c1.setTime(endDate);
            c2.setTime(startDate);
            if (c1.getTimeInMillis() < c2.getTimeInMillis()) {
                return "一年以下";
            }
            int year1 = c1.get(Calendar.YEAR);
            int year2 = c2.get(Calendar.YEAR);
            int month1 = c1.get(Calendar.MONTH);
            int month2 = c2.get(Calendar.MONTH);
            int day1 = c1.get(Calendar.DAY_OF_MONTH);
            int day2 = c2.get(Calendar.DAY_OF_MONTH);
            int yearInterval = year1 - year2;
            if (month1 < month2 || month1 == month2 && day1 < day2) {
                yearInterval--;
            }
            int monthInterval = (month1 + 12) - month2;
            monthInterval %= 12;
            int months = yearInterval * 12 + monthInterval;
            if (months < 12) {
                return "一年以下";
            } else if (months >= 12 && months < 36) {
                return "一年至三年";
            } else if (months >= 36 && months < 60) {
                return "三年至五年";
            } else {
                return "五年以上";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "一年以下";
        }
    }

    /**
     * @description: 格式化时间为yyyyMMddHHmmss
     * @param localDateTime
     * @return: java.lang.String
     * @author: zxq
     * @Date: 2020/9/27 14:06
     */
    public static String formatFullTime(LocalDateTime localDateTime) {
        return formatFullTime(localDateTime, FULL_TIME_PATTERN);
    }

    /**
     * @description:格式化时间为指定格式
     * @param localDateTime
     * @param pattern
     * @return: java.lang.String
     * @author: zxq
     * @Date: 2020/9/27 14:09
     */
    public static String formatFullTime(LocalDateTime localDateTime, String pattern) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        return localDateTime.format(dateTimeFormatter);
    }

    /**
     * @description:时间格式化,返回字符串格式
     * @param date
     * @param dateFormatType
     * @return: java.lang.String
     * @author: zxq
     * @Date: 2020/9/27 14:09
     */
    public static String getDateFormat(Date date, String dateFormatType) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormatType, Locale.CHINA);
        return simpleDateFormat.format(date);
    }

    /**
     * @description:将yyyy-MM-dd的时间字符串转换成Date类型的长字符串格式
     * @param strDate
     * @return: java.util.Date
     * @author: zxq
     * @Date: 2020/9/27 13:49
     */
    public static Date strToDate(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat(FORMAT);
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }

    /**
     * @description:将yyyy-MM-dd的时间字符串转换成Date类型的长字符串格式
     * @param strDate
     * @return: java.util.Date
     * @author: zxq
     * @Date: 2020/9/27 13:49
     */
    public static Date strToDate(String strDate,String pattern) {
        SimpleDateFormat formatter = new SimpleDateFormat(pattern);
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }

    /**
     * @description:
     * @param date
     * @param format
     * @return: java.lang.String
     * @author: zxq
     * @Date: 2020/9/27 14:10
     */
    public static String formatCSTTime(String date, String format) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(CST_TIME_PATTERN, Locale.US);
        Date usDate = simpleDateFormat.parse(date);
        return DateUtils.getDateFormat(usDate, format);
    }

    /**
     * @description:
     * @return: java.lang.Long
     * @author: zxq
     * @Date: 2020/9/27 14:10
     */
    public static Long getSeconds() throws ParseException {
        long now = System.currentTimeMillis();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-ddd");
        return (now - (format.parse(format.format(now)).getTime())) / 1000;
    }

    /**
     * @description:
     * @param instant
     * @param format
     * @return: java.lang.String
     * @author: zxq
     * @Date: 2020/9/27 14:10
     */
    public static String formatInstant(Instant instant, String format) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        return localDateTime.format(DateTimeFormatter.ofPattern(format));
    }

    /**
     * @description:获取者未来任意天内的日期数组
     * @param intervals
     * @param pattern
     * @return: java.util.ArrayList<java.lang.String>
     * @author: zxq
     * @Date: 2020/9/27 14:37
     */
    public static ArrayList<String> getDateFuture(int intervals, String pattern) {
        ArrayList<String> featureDaysList = new ArrayList<>();
        for (int i = 0; i <intervals; i++) {
            featureDaysList.add(getFutureDate(i,pattern));
        }
        return featureDaysList;
    }


    /**
     * @description: 获取未来 第 past 天的日期
     * @param past
     * @param pattern
     * @return: java.lang.String
     * @author: zxq
     * @Date: 2020/9/27 14:37
     */
    public static String getFutureDate(int past,String pattern) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        String result = format.format(today);
        return result;
    }

//    /**
//     * @description:获取当前时间往后延1天的时间,得到时间集合
//     * @param count
//     * @param fmt
//     * @return: java.util.List<java.lang.String>
//     * @author: zxq
//     * @Date: 2020/9/27 14:15
//     */
//    public static List<String> getDelayDateList(int count,String fmt) {
//        List<String> strList = new ArrayList<>();
//        try {
//            for(int i=0;i<count;i++) {
//                String ss = getDelayDate(i,fmt);
//                strList.add(ss);
//            }
//        } catch (Exception e) { }
//        return strList;
//    }
//
//    /**
//     * @description:获取当前时间往后延N天的时间
//     * @param day
//     * @param fmt
//     * @return: java.lang.String
//     * @author: zxq
//     * @Date: 2020/9/27 14:15
//     */
//    public static String getDelayDate(int day,String fmt) {
//        try {
//            SimpleDateFormat df = new SimpleDateFormat(fmt);
//            Date date = new Date();//取时间
//            Calendar calendar = Calendar.getInstance();
//            calendar.setTime(date); //需要将date数据转移到Calender对象中操作
//            calendar.add(Calendar.DATE, day);//把日期往后增加n天.正数往后推,负数往前移动
//            date = calendar.getTime();   //这个时间就是日期往后推一天的结果
//            String format = df.format(date);
//            return format;
//        }catch (Exception e){}
//        return "";
//    }


    /**
     * 比较时间大小
     * @param time1
     * @return
     * @throws ParseException
     */
    public static int compare(String date,String time1) throws ParseException
    {
        Calendar cal = Calendar.getInstance();
        String year=String.valueOf(cal.get(Calendar.YEAR));
        date = year+"-"+date;

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        Date dt1 = df.parse(date+" "+time1);

        Date now = new Date();
        if (dt1.getTime() > now.getTime() ){
            return 1;
        }else{
            return 0;
        }
    }

    /**
     * @description:把时间范围划分为等分
     * @param date1
     * @param date2
     * @param dataPattern
     * @param etc
     * @return: java.util.List<java.lang.String>
     * @author: zxq
     * @Date: 2020/9/27 14:50
     */
    public static List<String> splitDate(String date1, String date2, String dataPattern, Integer etc){
        //1.把时间变成时间戳
        List<String>  str = new ArrayList<>();
        long longs=strToSqlDate(date2,dataPattern)-strToSqlDate(date1,dataPattern);
        long single=longs/etc;
        for(int i=0;i<etc;i++){
            long a = strToSqlDate(date1,dataPattern)+(i*single);
            //再把时间戳变成标准的date形式
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dataPattern);
            Date date = new Date(a);
            str.add(simpleDateFormat.format(date));
        }
        return str;
    }

    public static long strToSqlDate(String strDate, String dateFormat) {
        SimpleDateFormat sf = new SimpleDateFormat(dateFormat);
        Date date = null;
        try {
            date = sf.parse(strDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        java.sql.Timestamp dateSQL = new java.sql.Timestamp(date.getTime());
        return dateSQL.getTime();
    }

    /**
     * @description:获取两个时间间隔1小时的时间集合
     * @param startHour
     * @param endHour
     * @return: java.util.List<java.lang.String>
     * @author: zxq
     * @Date: 2020/9/27 14:33
     */
    public static List<String> spiltTimeByHour(String startHour, String endHour) {
        List<String> retTime = new ArrayList<>();
        try {

            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
            long difTime = (sdf.parse(endHour).getTime() - sdf.parse(startHour).getTime()) / (1000);
            if(difTime<0){
                difTime = (sdf.parse("24:00").getTime() - sdf.parse(startHour).getTime()) / (1000);
                difTime += (sdf.parse(endHour).getTime() - sdf.parse("00:00").getTime()) / (1000);

            }else{
                difTime = (sdf.parse(endHour).getTime() - sdf.parse(startHour).getTime()) / (1000);
            }
            int n = Math.abs(Integer.valueOf(String.valueOf((difTime / 60 / 30))));

            Calendar c = Calendar.getInstance();
            c.setTime(sdf.parse(startHour));
            for (int i = 1; i < n; i++) {
                c.add(Calendar.MINUTE, 30);
                retTime.add(sdf.format(c.getTime()));
            }
        } catch (ParseException e) {
        }
        Collections.sort(retTime);
        return retTime;
    }

    /**
     * @description:获取当前时间是星期几
     * @param dt
     * @return: java.lang.String
     * @author: zxq
     * @Date: 2020/9/27 14:12
     */
    public static String getWeekByDate(String dt) {
        try {
            SimpleDateFormat dateFm = new SimpleDateFormat("yyyy-MM-dd");
            Date nowDate = dateFm.parse(dt);
            String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
            Calendar cal = Calendar.getInstance();
            cal.setTime(nowDate);
            int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
            if (w < 0) {
                w = 0;
            }
            return weekDays[w];
        }catch (Exception e){}
        return "未知";
    }

}
View Code

 

  

 

posted @ 2020-09-27 16:02  姜饼攻城狮  阅读(116)  评论(0编辑  收藏  举报