java 时间工具类

时间工具类

    对于老的项目,一般都是用SimpleDateFormat,代码进行扫描的时候,会有线程安全问题。一般有两种解决方案,一是使用第三方时间插件,如Joda-Time,第二是使用jdk8的LocalDate,这里,写了两个工具类提供参考。

Joda-Time

public class JodaTimeUtil {

    private static final String FORMAT_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";

    /**
     * 获取当前系统时间
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String getCurrentTime() {
        DateTime dt = new DateTime();
        String time = dt.toString(FORMAT_TIME_PATTERN);
        return time;
    }

    /**
     * 获取系统当前时间按照指定格式返回
     * @param pattern  yyyy/MM/dd hh:mm:a
     * @return
     */
    public static String getCurrentTimePattern(String pattern) {
        DateTime dt = new DateTime();
        String time = dt.toString(pattern);
        return time;
    }

    /**
     * 获取当前日期
     * @return
     */
    public static String getCurrentDate() {
        DateTime dt = new DateTime();
        String date = dt.toString(FORMAT_TIME_PATTERN);
        return date;
    }

    /**
     * 获取当前日期按照指定格式
     * @param pattern
     * @return
     */
    public static String getCurrentDatePattern(String pattern) {
        DateTime dt = new DateTime();
        String date = dt.toString(pattern);
        return date;
    }


    /**
     * 获取指定时间
     * @param year 年
     * @param month 月
     * @param day 天
     * @param hour 小时
     * @param minute 分钟
     * @param seconds 秒
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String getPointTime(Integer year, Integer month, Integer day, Integer hour, Integer minute, Integer seconds) {
        DateTime dt = new DateTime(year, month, day, hour, minute, seconds);
        String date = dt.toString(FORMAT_TIME_PATTERN);
        return date;
    }

    /**
     *
     * @param year 年
     * @param month 月
     * @param day 天
     * @param hour 小时
     * @param minute 分钟
     * @param seconds 秒
     * @param parrten 自定义格式
     * @return parrten
     */
    public static String getPointTimePattern(Integer year, Integer month, Integer day, Integer hour, Integer minute, Integer seconds, String parrten) {
        DateTime dt = new DateTime(year, month, day, hour, minute, seconds);
        String date = dt.toString(parrten);
        return date;
    }

    /**
     * 获取指定日期
     * @param year
     * @param month
     * @param day
     * @return
     */
    public static String getPointDate(Integer year, Integer month, Integer day) {
        LocalDate dt = new LocalDate(year, month, day);
        String date = dt.toString(FORMAT_TIME_PATTERN);
        return date;
    }

    /**
     * 获取指定日期 返回指定格式
     * @param year
     * @param month
     * @param day
     * @param parrten
     * @return
     */
    public static String getPointDatParrten(Integer year, Integer month, Integer day, String parrten) {
        LocalDate dt = new LocalDate(year, month, day);
        String date = dt.toString(parrten);
        return date;
    }

    /**
     * 获取当前是一周星期几
     * @return
     */
    public static String getWeek() {
        DateTime dts = new DateTime();
        String week = null;
        switch (dts.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                week = "星期日";
                break;

            case DateTimeConstants.MONDAY:
                week = "星期一";
                break;

            case DateTimeConstants.TUESDAY:
                week = "星期二";
                break;
            case DateTimeConstants.WEDNESDAY:
                week = "星期三";
                break;
            case DateTimeConstants.THURSDAY:
                week = "星期四";
                break;
            case DateTimeConstants.FRIDAY:
                week = "星期五";
                break;
            case DateTimeConstants.SATURDAY:
                week = "星期六";
            default:
                break;
        }
        return week;
    }

    /**
     * 获取指定时间是一周的星期几
     * @param year
     * @param month
     * @param day
     * @return
     */
    public static String getWeekPoint(Integer year, Integer month, Integer day) {
        LocalDate dts = new LocalDate(year, month, day);
        String week = null;
        switch (dts.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                week = "星期日";
                break;
            case DateTimeConstants.MONDAY:
                week = "星期一";
                break;
            case DateTimeConstants.TUESDAY:
                week = "星期二";
                break;
            case DateTimeConstants.WEDNESDAY:
                week = "星期三";
                break;
            case DateTimeConstants.THURSDAY:
                week = "星期四";
                break;
            case DateTimeConstants.FRIDAY:
                week = "星期五";
                break;
            case DateTimeConstants.SATURDAY:
                week = "星期六";
                break;

            default:
                break;
        }
        return week;
    }


    /**
     *获取当前时间前几天时间,按指定格式返回
     * @param days
     * @return
     */
    public static String forwardDay(Integer days, String format) {
        DateTime dt = new DateTime();
        DateTime y = dt.minusDays(days);
        return y.toString(format);
    }

    /**
     *获取当前时间前几天时间
     * @param days
     * @return
     */
    public static Date forwardDay(Integer days) {
        DateTime dt = new DateTime();
        DateTime y = dt.minusDays(days);
        return y.toDate();
    }

    /**
     * 获取指定时间之后或者之前的某一天00:00:00 默认返回当天
     * @param days
     * @return
     */
    public static Date day00(Integer days, String date, String zimeZone) throws Throwable {
        DateTime dt;
        TimeZone timeZone;
        try {
            if (StringUtils.isBlank(zimeZone)) {
                timeZone = TimeZone.getDefault();
            } else {
                timeZone = TimeZone.getTimeZone(zimeZone);
            }
            if (StringUtils.isBlank(date)) {
                dt = new DateTime().withZone(DateTimeZone.forTimeZone(timeZone)).toLocalDateTime().toDateTime();
            } else {
                dt = new DateTime(date).withZone(DateTimeZone.forTimeZone(timeZone)).toLocalDateTime().toDateTime();
            }
        } catch (Exception e) {
            throw new Throwable(e);
        }

        DateTime y = dt.minusDays(days).withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0);
        return y.toDate();
    }

    /**
     *获取指定时间之后或者之前的某一天23:59:59 默认返回当天
     * @param days 偏移量
     * @return
     */
    public static Date day59(Integer days, String date, String zimeZone) throws Throwable {
        DateTime dt;
        TimeZone timeZone;
        try {
            if (StringUtils.isBlank(zimeZone)) {
                timeZone = TimeZone.getDefault();
            } else {
                timeZone = TimeZone.getTimeZone(zimeZone);
            }
            if (StringUtils.isBlank(date)) {

                dt = new DateTime().withZone(DateTimeZone.forTimeZone(timeZone)).toLocalDateTime().toDateTime();
            } else {
                dt = new DateTime(date).withZone(DateTimeZone.forTimeZone(timeZone)).toLocalDateTime().toDateTime();
            }
        } catch (Exception e) {
            throw new Throwable(e);
        }
        DateTime y = dt.minusDays(days).withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59);
        return y.toDate();
    }

    /**
     * 计算两个时间相差多少天
     * @param startDate
     * @param endDate
     * @return
     */
    public static Integer diffDay(Date startDate, Date endDate) {
        if (startDate == null || endDate == null) {
            return null;
        }
        DateTime dt1 = new DateTime(startDate);
        DateTime dt2 = new DateTime(endDate);
        int day = Days.daysBetween(dt1, dt2).getDays();
        return Math.abs(day);
    }

    /**
     * 获取某月之前,之后某一个月最后一天,24:59:59
     * @return
     */
    public static Date lastDay(Date date, Integer month) {
        DateTime dt1;
        if (month == null) {
            month = 0;
        }
        if (date == null) {
            dt1 = new DateTime().minusMonths(month);
        } else {
            dt1 = new DateTime(date).minusMonths(month);
        }
        DateTime lastDay = dt1.dayOfMonth().withMaximumValue().
                withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59);
        return lastDay.toDate();
    }

    /**
     *获取某月月之前,之后某一个月第一天,00:00:00
     * @return
     */
    public static Date firstDay(Date date, Integer month) {
        DateTime dt1;
        if (month == null) {
            month = 0;
        }
        if (date == null) {
            dt1 = new DateTime().minusMonths(month);
        } else {
            dt1 = new DateTime(date).minusMonths(month);
        }
        DateTime lastDay = dt1.dayOfMonth().withMinimumValue().
                withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0);
        return lastDay.toDate();
    }

    public static Date addDay(Date date, int offset) {
        DateTime dt1;
        if (date == null) {
            dt1 = new DateTime().plusDays(offset);
            return dt1.toDate();
        }
        dt1 = new DateTime(date).plusDays(offset);
        return dt1.toDate();

    }

    /**
     * 传入日期时间与当前系统日期时间的比较,
     * 若日期相同,则根据时分秒来返回 ,
     * 否则返回具体日期
     * @return 日期或者 xx小时前||xx分钟前||xx秒前
     */
    public static String getNewUpdateDateString(Date now, Date createDate) {
        if (now == null || createDate == null) {
            return null;
        }
        Long time = (now.getTime() - createDate.getTime());
        if (time > (24 * 60 * 60 * 1000)) {
            return time / (24 * 60 * 60 * 1000) + "天前";
        } else if (time > (60 * 60 * 1000)) {
            return time / (60 * 60 * 1000) + "小时前";
        } else if (time > (60 * 1000)) {
            return time / (60 * 1000) + "分钟前";
        } else if (time >= 1000) {
            return time / 1000 + "秒前";
        }
        return "刚刚";
    }

    /**
     *功能描述 字符串转为时间
     * @author gilbert
     * @date 2020/7/2
     * @param [dateTimeStr, formatStr]
     * @return java.util.Date
     */
    public static Date stringToDate(String dateTimeStr, String formatStr){
        DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(formatStr);
        DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr);
        return dateTime.toDate();
    }

    public static void main(String[] args) {
        System.out.println(stringToDate("2020-07-02 10:35:32","yyyy-MM-dd HH:mm:ss"));
    }

LocalDateUtil

public class LocalDateUtil {

    /**
     * 时间格式yyyy-MM-dd HH:mm:ss
     */
    private final static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    /**
     * 时间格式yyyyMMddHHmmss
     */
    private final static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    /**
     * 时间格式yyyy-MM-dd
     */
    private final static String YYYY_MM_DD = "yyyy-MM-dd";

    /**
     * 时间格式yyyyMMdd
     */
    private final static String YYYYMMDD = "yyyyMMdd";

    /**
     * 功能描述 Date类型转换为LocalDateTime类型
     *
     * @param date
     * @return java.time.LocalDateTime
     * @author gilbert
     * @date 2019/9/23
     */
    public static LocalDateTime convertDateToLDT(Date date) {
        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    }

    /**
     * 功能描述 LocalDateTime类型转换为Date类型
     *
     * @param time
     * @return java.util.Date
     * @author gilbert
     * @date 2019/9/23
     */
    public static Date convertLDTToDate(LocalDateTime time) {
        return Date.from(time.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * 功能描述 获取指定日期的毫秒
     *
     * @param time
     * @return java.lang.Long
     * @author gilbert
     * @date 2019/9/23
     */
    public static Long getMilliByTime(LocalDateTime time) {
        return time.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

    /**
     * 功能描述 获取指定日期的秒
     *
     * @param time
     * @return java.lang.Long
     * @author gilbert
     * @date 2019/9/23
     */
    public static Long getSecondsByTime(LocalDateTime time) {
        return time.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();
    }

    /**
     * 功能描述 获取指定时间的指定格式
     *
     * @param time
     * @param pattern
     * @return java.lang.String
     * @author gilbert
     * @date 2019/9/23
     */
    public static String formatTime(LocalDateTime time, String pattern) {
        return time.format(DateTimeFormatter.ofPattern(pattern));
    }


    /**
     * 功能描述 获取当前时间的指定格式
     *
     * @param [pattern]
     * @return java.lang.String
     * @author gilbert
     * @date 2019/9/23
     */
    public static String formatNow(String pattern) {
        return formatTime(LocalDateTime.now(), pattern);
    }

    /**
     * 功能描述 日期加上一个数,根据field不同加不同值,field为ChronoUnit.*
     * @author gilbert
     * @date 2019/9/23
     * @param time
     * @param number
     * @param field
     * @return java.time.LocalDateTime
     * @author gilbert
     * @date 2019/9/23
     */
    public static LocalDateTime plus(LocalDateTime time, long number, TemporalUnit field) {
        return time.plus(number, field);
    }

    /**
     *功能描述 日期减去一个数,根据field不同减不同值,field参数为ChronoUnit.*
     * @author gilbert
     * @date 2019/9/23
     * @param time
     * @param number
     * @param field
     * @return java.time.LocalDateTime
     */
    public static LocalDateTime minu(LocalDateTime time, long number, TemporalUnit field) {
        return time.minus(number, field);
    }

    /**
     *功能描述 获取两个日期的差  field参数为ChronoUnit.*
     * @author gilbert
     * @date 2019/9/23
     * @param time
     * @param number
     * @param field
     * @return long
     */
    public static long betweenTwoTime(LocalDateTime startTime, LocalDateTime endTime, ChronoUnit field) {
        Period period = Period.between(LocalDate.from(startTime), LocalDate.from(endTime));
        if (field == ChronoUnit.YEARS) return period.getYears();
        if (field == ChronoUnit.MONTHS) return period.getMonths();
        if (field == ChronoUnit.DAYS) return period.getDays();
        return field.between(startTime, endTime);
    }

    /**
     *功能描述 获取一天的开始时间
     * @author gilbert
     * @date 2019/9/23
     * @param time
     * @return java.time.LocalDateTime
     */
    public static LocalDateTime getDayStart(LocalDateTime time) {
        return time.withHour(0)
                .withMinute(0)
                .withSecond(0)
                .withNano(0);
    }

    /**
     *功能描述 获取一天的结束时间
     * @author gilbert
     * @date 2019/9/23
     * @param time
     * @return java.time.LocalDateTime
     */
    public static LocalDateTime getDayEnd(LocalDateTime time) {
        return time.withHour(23)
                .withMinute(59)
                .withSecond(59)
                .withNano(999999999);
    }

    /**
     *功能描述 字符串时间转换为LocalDateTime时间
     * @author gilbert
     * @date 2019/9/23
     * @param [time, format]
     * @return java.time.LocalDateTime
     */
    public static LocalDateTime parseStringToDateTime(String time, String pattern) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern);
        return LocalDateTime.parse(time, df);
    }

    /**
     *功能描述 获取相加number后时间的那个月第一天
     * @author gilbert
     * @date 2019/9/23
     * @param time
     * @param number
     * @param field
     * @return java.time.LocalDateTime
     */
    public static LocalDateTime getNumMonthFirstDay(LocalDateTime time, long number, ChronoUnit field){
        LocalDateTime ldt = time.plus(number, field);
        return ldt.with(TemporalAdjusters.firstDayOfMonth());
    }

    /**
     *功能描述 获取相加number后时间的那个月最后一天
     * @author gilbert
     * @date 2019/9/23
     * @param time
     * @param number
     * @param field
     * @return java.time.LocalDateTime
     */
    public static LocalDateTime getNumMonthLastDay(LocalDateTime time, long number, ChronoUnit field){
        LocalDateTime ldt = time.plus(number, field);
        return ldt.with(TemporalAdjusters.lastDayOfMonth());
    }

    /**
     *功能描述 时间比较
     * @author gilbert
     * @date 2019/9/23
     * @param before
     * @param after
     * @return boolean true,before在after时间之前;false,before在after时间之后
     */
    public static boolean isBefore(LocalDateTime before, LocalDateTime after){
        return before.isBefore(after);
    }

    /**
     *功能描述 时间比较
     * @author gilbert
     * @date 2019/9/23
     * @param time
     * @return boolean true,before在after时间之后;false,before在after时间之前
     */
    public static boolean isAfter(LocalDateTime before, LocalDateTime after){
        return before.isAfter(after);
    } 

    /**
     *功能描述 时间是否相等
     * @author gilbert
     * @date 2019/9/23
     * @param time
     * @return boolean true,两个时间相等;false,两个时间不相等
     */
    public static boolean isEqual(LocalDateTime before, LocalDateTime after){
        return before.isEqual(after);
    }

    /**
     *功能描述 时间是否相等(年月日)
     * @author gilbert
     * @date 2019/9/23
     * @param before
     * @param after
     * @return boolean true,两个时间相等;false,两个时间不相等
     */
    public static boolean isEqualByLocalDate(LocalDateTime before, LocalDateTime after){
        return LocalDate.of(before.getYear(),before.getMonthValue(),before.getDayOfMonth()).isEqual(LocalDate.of(after.getYear(),after.getMonthValue(),after.getDayOfMonth()));
    }

    /**
     *功能描述 时间是否相等(月日)
     * @author gilbert
     * @date 2019/9/23
     * @param before
     * @param after
     * @return boolean true,两个时间相等;false,两个时间不相等
     */
    public static boolean isEqualByMonthDay(LocalDateTime before, LocalDateTime after){
        return MonthDay.of(before.getMonthValue(),before.getDayOfMonth()).equals(MonthDay.of(after.getMonthValue(),after.getDayOfMonth()));
    }

    /**
     *功能描述
     * @author gilbert
     * @date 2019/9/23
     * @param time
     * @return boolean
     */
    public static boolean isLeapYear(LocalDateTime time){
        return LocalDate.of(time.getYear(),time.getMonthValue(),time.getDayOfMonth()).isLeapYear();
    }

    /**
     *功能描述 本月第一天
     * @author gilbert
     * @date 2019/10/11
     * @param []
     * @return java.time.LocalDateTime
     */
    public static LocalDateTime getMonthFirsDay(){
        LocalDateTime localDateTime = LocalDateTime.of(LocalDate.now(),LocalTime.MIN);
        return localDateTime.with(TemporalAdjusters.firstDayOfMonth());
    }

    /**
     *功能描述 本月第后天
     * @author gilbert
     * @date 2019/10/11
     * @param []
     * @return java.time.LocalDateTime
     */
    public static LocalDateTime getMonthLastDay(){
        LocalDateTime localDateTime = LocalDateTime.now();
        return localDateTime.with(TemporalAdjusters.lastDayOfMonth());
    }
	
	/**
	 *功能描述 获取昨天最大时间
	 * @author gilbert
	 * @date 2019/10/11
	 * @param
	 * @return java.time.LocalDateTime
	 */
	public static LocalDateTime getLastDayMax(){
		LocalDateTime lastDateTime = minu(LocalDateTime.now(),1, ChronoUnit.DAYS);
		LocalDate localDate = lastDateTime.toLocalDate();
		return LocalDateTime.of(localDate,LocalTime.MAX);
	}

	/**
	 *功能描述 获取当前时间本周一的最小时间
	 * @author gilbert
	 * @date 2019/10/11
	 * @param
	 * @return java.time.LocalDateTime
	 */
	public static LocalDateTime getNowTimeWeekFirsDay(){
		TemporalAdjuster FIRST_OF_WEEK = TemporalAdjusters.ofDateAdjuster(localDate -> localDate.minusDays(localDate
				.getDayOfWeek().getValue() - DayOfWeek.MONDAY.getValue()));
		return LocalDateTime.of(LocalDate.now(), LocalTime.MIN).with(FIRST_OF_WEEK);
	}

    public static void main(String[] args) {

        System.out.println(convertDateToLDT(new Date()));

        System.out.println(formatTime(LocalDateTime.of(2019, 9, 23, 11, 30, 58),YYYY_MM_DD_HH_MM_SS));

        System.out.println(formatTime(LocalDateTime.now(),YYYY_MM_DD_HH_MM_SS));

        System.out.println(formatNow(YYYY_MM_DD_HH_MM_SS));

        System.out.println(formatTime(plus(LocalDateTime.now(),20,ChronoUnit.MINUTES),YYYY_MM_DD_HH_MM_SS));

        System.out.println(formatTime(minu(LocalDateTime.now(),2,ChronoUnit.MINUTES),YYYY_MM_DD_HH_MM_SS));

        System.out.println("相差多少分:" + betweenTwoTime(LocalDateTime.now(),LocalDateTime.of(2019,9,23,11,40,00),ChronoUnit.MINUTES));

        System.out.println("相差多少天:" + betweenTwoTime(LocalDateTime.now(),LocalDateTime.of(2019,9,22,14,40,00),ChronoUnit.DAYS));

        System.out.println("相差多少月:" + betweenTwoTime(LocalDateTime.now(),LocalDateTime.of(2019,8,22,14,40,00),ChronoUnit.MONTHS));

        System.out.println(formatTime(getDayStart(LocalDateTime.now()),YYYY_MM_DD_HH_MM_SS));

        System.out.println(formatTime(getDayEnd(LocalDateTime.now()),YYYY_MM_DD_HH_MM_SS));

        System.out.println(parseStringToDateTime("2019-09-23 11:56:59",YYYY_MM_DD_HH_MM_SS));

        System.out.println(getNumMonthFirstDay(LocalDateTime.now(),8,ChronoUnit.DAYS));

        System.out.println(getNumMonthLastDay(LocalDateTime.now(),8,ChronoUnit.DAYS));

        System.out.println(isBefore(LocalDateTime.of(2019,9,23,13,14,00),LocalDateTime.now()));

        System.out.println(isAfter(LocalDateTime.of(2019,9,23,13,14,00),LocalDateTime.now()));

        System.out.println(isEqual(LocalDateTime.of(2019,9,23,13,17),LocalDateTime.now()));

        System.out.println(isEqualByLocalDate(LocalDateTime.of(2019,9,23,16,30),LocalDateTime.of(2019,9,23,13,30)));

        System.out.println(isLeapYear(LocalDateTime.of(2019,9,23,13,17)));

        System.out.println(isEqualByMonthDay(LocalDateTime.of(2019,9,23,16,30),LocalDateTime.of(2021,9,23,13,30)));
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值