Java--工具类(日期/时间)

依赖

后端接收
@ApiModelProperty(value = "开始时间")
// 该注解放在接收实体中,前端String类型传入,后端Date类型接收。注意:若前端格式与后端不匹配,会抛格式转换异常。
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") 
private LocalDateTime startTime;


// 该注解放在返回实体中。
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") // 将Date类型的时间转成字符串
时间
package com.lhj.finance.commons.util;


import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @Desc DateUtils 日期/时间
 * @Author lihongjiang
 * @Date 2020/8/10 9:29
 **/
@Slf4j
public class DateUtils {

    /**
     * 中线MID_LINE
     **/
    public static final String MID_LINE_ALL = "yyyy-MM-dd HH:mm:ss";
    public static final String NO_LINE_ALL = "yyyyMMddHHmmss";
    public static final String MID_LINE_YMD = "yyyy-MM-dd";
    public static final String NO_LINE_YMD = "yyyyMMdd";
    /**
     * 冒号COLON
     **/
    public static final String COLON_HMS = "HH:mm:ss";
    public static final String NO_COLON_HMS = "HHmmss";


    /**
     * 日期转字符串
     * @param date 日期
     * @param format 转换格式
     * @return 日期字符串
     **/
    public static String format(Date date, String format){
        return new SimpleDateFormat(format).format(date);
    }
    /**
     * 字符串转日期
     * @param dateStr 日期字符串
     * @return 日期
     **/
    public static Date parse(String dateStr, String format) {
        Date parse = null;
        try {
            parse = new SimpleDateFormat(format).parse(dateStr);
        } catch (ParseException e) {
            log.error("日期格式转换异常,{}", e.getMessage());
        }
        return parse;
    }
    /**
     * UTC转GST
     * @param utc 世界标准时间UTC(格式:"2019-07-10T16:00:00.000Z")
     * @param format 时间格式
     * @return GST 北京时间
     **/
    public static String utcToGst(String utc, String format) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format);
        ZonedDateTime zdt = ZonedDateTime.parse(utc);
        // UTC时间加8小时,转为北京时间
        LocalDateTime localDateTime = zdt.toLocalDateTime().plusHours(8);
        return dtf.format(localDateTime);
    }
    /**
     * GST转UTC
     * @param date 北京时间GST
     * @param format 时间格式
     * @return UTC 世界标准时间UTC
     **/
    public static String gstToUtc(Date date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+0"));
        return sdf.format(date);
    }


    /**
     * 加减(年月日)
     * @param date 原始的日期
     * @param year 年数
     * @param month 月数
     * @param day 日数
     * @return 日期
     **/
    public static Date addMinusYearMonthDay(Date date, int year, int month, int day) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.YEAR, year);
        cal.add(Calendar.MONTH, month);
        cal.add(Calendar.DATE, day);
        return cal.getTime();
    }
    /**
     * 加减(时分秒)
     * @param date 原始的日期
     * @param hour 时数
     * @param minute 分数
     * @param second 秒数
     * @return 日期
     **/
    public static Date addMinusHourMonthSecond(Date date, int hour, int minute, int second) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.HOUR, hour);
        cal.add(Calendar.MINUTE, minute);
        cal.add(Calendar.SECOND, second);
        return cal.getTime();
    }
    /**
     * 加减(周)
     * @param date 原始的日期
     * @param week 周数
     * @return 日期
     **/
    public static Date addMinusWeek(Date date, int week) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DAY_OF_WEEK, week);
        return cal.getTime();
    }


    /**
     * 时间差(年,月,日,时,分,秒)
     * @param start 开始时间
     * @param end 结束时间
     * @return list 年,月,日,时,分,秒
     **/
    public static List<Integer> timeAllDiff(Date start, Date end) {
        // 年月日
        List<Integer> ymdList = yearMonthDayDiff(start, end);
        // 时分秒
        ymdList.addAll(hourMinuteSecondDiff(start, end));
        return ymdList;
    }
    /**
     * 时间差(年,月,日)
     * @param start 开始时间
     * @param end 结束时间
     * @return list 年,月,日
     **/
    public static List<Integer> yearMonthDayDiff(Date start, Date end) {
        // 若后者小于前者,则交换位置。
        List<Date> dates = compareExchangeDate(start, end);
        // 计算时间差
        Period period = Period.between(toLocalDate(dates.get(0)), toLocalDate(dates.get(1)));
        // 返回年月日
        List<Integer> ymdList = new ArrayList<>();
        ymdList.add(period.getYears());
        ymdList.add(period.getMonths());
        ymdList.add(period.getDays());
        return ymdList;
    }
    /**
     * 时间差(月,日)
     * @param start 开始时间
     * @param end 结束时间
     * @return 月,日
     **/
    public static List<Integer> monthDayDiff(Date start, Date end) {
        // 若后者小于前者,则交换位置。
        List<Date> dates = compareExchangeDate(start, end);
        // 计算时间差
        Period period = Period.between(toLocalDate(dates.get(0)), toLocalDate(dates.get(1)));
        List<Integer> ymdList = new ArrayList<>();
        ymdList.add(period.getYears() * 12 + period.getMonths());
        ymdList.add(period.getDays());
        return ymdList;
    }
    /**
     * 时间差(日,时,分,秒)
     * @param start 开始时间
     * @param end 结束时间
     * @return list 日,时,分,秒
     **/
    public static List<Integer> dayHourMinuteSecondDiff(Date start, Date end) {
        // 获取时间差(秒)
        long second = millisecondDiff(start, end) / 1000;
        // 计算(日,时,分,秒)
        int dd = (int) second / (60 * 60 * 24);
        int hh = (int) (second - dd * 60 * 60 * 24) / (60 * 60);
        int mm = (int) (second - dd * 60 * 60 * 24 - hh * 60 * 60) / (60);
        int ss = (int) (second - dd * 60 * 60 * 24 - hh * 60 * 60 - mm * 60);
        // 返回(日,时,分,秒)
        List<Integer> ymdList = new ArrayList<>();
        ymdList.add(dd);
        ymdList.add(hh);
        ymdList.add(mm);
        ymdList.add(ss);
        return ymdList;
    }
    /**
     * 时间差(日)
     * @param start 开始时间
     * @param end 结束时间
     * @param num 小数点保留位数
     * @return 小时
     **/
    public static BigDecimal dayDiff(Date start, Date end, int num) {
        return quotient(millisecondDiff(start, end), (1000 * 60 * 60 * 24), num);
    }
    /**
     * 时间差(时,分,秒)
     * @param start 开始时间
     * @param end 结束时间
     * @return list 时,分,秒
     **/
    public static List<Integer> hourMinuteSecondDiff(Date start, Date end) {
        // 获取日期信息(日,时,分,秒)
        List<Integer> ymdList = dayHourMinuteSecondDiff(start, end);
        // 删除日数据
        ymdList.remove(0);
        return ymdList;
    }
    /**
     * 时间差(时)
     * @param start 开始时间
     * @param end 结束时间
     * @param num 小数点保留位数
     * @return 小时
     **/
    public static BigDecimal hourDiff(Date start, Date end, int num) {
        return quotient(millisecondDiff(start, end), (1000 * 60 * 60), num);
    }
    /**
     * 时间差(分)
     * @param start 开始时间
     * @param end 结束时间
     * @param num 小数点保留位数
     * @return 分钟(四舍五入)
     **/
    public static BigDecimal minuteDiff(Date start, Date end, int num) {
        return quotient(millisecondDiff(start, end), (1000 * 60), num);
    }
    /**
     * 时间差(秒)
     * @param start 开始时间
     * @param end 结束时间
     * @param num 小数点保留位数
     * @return 秒(四舍五入)
     **/
    public static BigDecimal secondDiff(Date start, Date end, int num) {
        return quotient(millisecondDiff(start, end), (1000), num);
    }
    /**
     * 时间差(毫秒)
     * @param start 开始时间
     * @param end 结束时间
     * @return 毫秒
     **/
    public static Long millisecondDiff(Date start, Date end) {
        // 比较/并换日期
        List<Date> dates = compareExchangeDate(start, end);
        // 计算差值,返回时间差
        return dates.get(1).getTime() - dates.get(0).getTime();
    }


    /**
     * 是否在时间范围内
     * @param startDate 开始范围
     * @param endDate 结束范围
     * @param date 指定时间
     * @return 是/否
     */
    public static boolean between(Date startDate, Date endDate, Date date) {
        // 比较/交换日期
        List<Date> dates = compareExchangeDate(startDate, endDate);
        // 大于等于开始日期,小于等于结束日期
        return date.after(dates.get(0)) && date.before(dates.get(1));
    }
    /**
     * 被除数 / 除数 = 商
     * @param dividend 被除数
     * @param divisor 除数
     * @param num 小数点位(大于0时四舍五入;否则反之;)
     * @return 商
     **/
    public static BigDecimal quotient(long dividend, long divisor, int num) {
        if(num>0){
            return BigDecimal.valueOf(dividend).divide(BigDecimal.valueOf(divisor), num, BigDecimal.ROUND_HALF_UP);
        }
        return BigDecimal.valueOf(dividend).divideToIntegralValue(BigDecimal.valueOf(divisor));
    }
    /**
     * 比较/交换日期
     * @param start 开始日期
     * @param end 结束日期
     * @return list
     **/
    public static List<Date> compareExchangeDate(Date start, Date end){
        // 若后者小于前者,则交换位置。
        if (end.compareTo(start)<0) {
            Date tmp = end;
            end = start;
            start = tmp;
        }
        List<Date> dates = new ArrayList<>();
        dates.add(start);
        dates.add(end);
        return dates;
    }
    /**
     * 平年或闰年
     * @param date 日期
     * @return 平年normal / 闰年leap
     **/
    public static String normalOrLeapYear(Date date) {
        String yearStr = "normal";
        // 获取年份
        LocalDate localDate = toLocalDate(date);
        int year = localDate.getYear();
        int a = year % 4;
        int b = year % 100;
        int c = year % 400;
        // 计算闰年
        if(a==0 && b!=0 || c==0) {
            yearStr = "leap";
        }
        return yearStr;
    }

    /**
     * LocalDate 转 Date
     * @param localDate 本地时间
     * @return Date
     **/
    public static Date toDate(LocalDate localDate) {
        return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
    }
    /**
     * LocalDateTime 转 DateTime
     * @param localDateTime 本地时间
     * @return Date
     **/
    public static Date toDateTime(LocalDateTime localDateTime) {
        return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
    }
    /**
     * Date 转 LocalDate
     * @param date 时间
     * @return Date
     **/
    public static LocalDate toLocalDate(Date date) {
        return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
    }
    /**
     * DateTime 转 LocalDateTime
     * @param date 时间
     * @return Date
     **/
    public static LocalDateTime toLocalDateTime(Date date) {
        return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    /**
     * 时间转时间戳
     * @param date 时间
     * @return 时间戳
     **/
    public static Long dateToTimestamp(Date date){
        return date.getTime();
    }

    /**
     * 时间戳转时间
     * @param timestamp 时间戳
     * @return 时间
     **/
    public static Date timestampToDate(Long timestamp){
        return new Date(timestamp);
    }

	/**
     * 计算时间戳差(毫秒)
     * @param startTimestamp 时间戳
     * @return 时间戳差
     **/
    public static Long timeDiff(Long startTimestamp){
        return System.currentTimeMillis() - startTimestamp;
    }

    /**
     * 计算时间戳差(毫秒)
     * @param stopWatch 时间对象
     * @return 时间戳差
     **/
    public static Long timeDiff(StopWatch stopWatch){
        stopWatch.stop();
        return stopWatch.getTotalTimeMillis();
    }

	/**
     * 原始时间格式为字符串,转Date类型
     * @param oirStr 原始时间格式的字符串 Sep 09 2020
     * @return 时间类型
     **/
    public static Date strToDate(String oirStr){
        return new Date(oirStr);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

你默然

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值