JAVA 实用时间工具类

今天本汪把一个自己一直在使用的时间工具类贡献出来,希望帮到有需要的朋友。 这个时间工具类,基本包含了java 开发工作中,会遇到的所有情形:
1、获取当前Date型日期;获取当前日期, 默认格式为yyyy-MM-dd;
2、日期型字符串转化为日期 格式。
3、计算两个时间差。
4、根据具体年份周数获取日期范围。
5、校验开始时间是否大于结束时间。
6、获取当前时间,日期以1970/1/1 存储。
7、在日期时间基础上增加N分钟。
8、获取一周开始到结束的list集合。
9、当前时间向推几小时。

package com.cccc.common.utils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateFormatUtils;

/**
 * 时间工具类
 *
 * @author yuezejian
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

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

    //modified by Yue Zejian 2021/7/26
    public static String HH_MM_SS = "HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate(Date date)
    {
        return dateTimeNow(YYYY_MM_DD, date);
    }


    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTimeNow(final String format, Date date)
    {
        return parseDateToStr(format, date);
    }


    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static String toStandardDateString ( Date date) {
        return parseDateToStr(YYYY_MM_DD_HH_MM_SS,date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }


    /**
     * 根据具体年份周数获取日期范围
     * @param year 年份
     * @param week 周数
     * @param targetNum 第几天开始
     * @return
     */
    public static List<String> getWeekDays(int year, int week, int targetNum) {

        // 计算目标周数
        if (week + targetNum > 52) {
          year++;
          week += targetNum - 52;
        } else if (week + targetNum <= 0) {
          year--;
          week += targetNum + 52;
        } else {
          week += targetNum;
        }

        SimpleDateFormat sdf=new SimpleDateFormat(YYYY_MM_DD);
        Calendar cal=Calendar.getInstance();

        // 设置每周的开始日期
        cal.setFirstDayOfWeek(Calendar.SUNDAY);

        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.WEEK_OF_YEAR, week);

        cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
        String beginDate = sdf.format(cal.getTime());

        cal.add(Calendar.DAY_OF_WEEK, 6 );
        String endDate = sdf.format(cal.getTime());

        List<String> list = new ArrayList<>();
        list.add(beginDate);
        list.add(endDate);
        return list;
    }

    /**
     * 校验开始时间是否大于结束时间
     *
     * @param startTime 开始时间字符串
     * @param endTime 结束时间字符串
     * @param format 格式
     * @auther Yue Zejian 2021/7/26
     * @return
     */
    public static boolean checkTimeRange(String startTime, String endTime, String format) {
        try {

            SimpleDateFormat sdf = new SimpleDateFormat(format);
            Date startDate = null;
            Date endDate = null;

            startDate = sdf.parse(startTime);
            endDate = sdf.parse(endTime);

            if (startDate.after(endDate)) { //startDate是否在endTime之后,为true 表示  startTime>endTime
                return true;
            } else {
                return false;
            }
            /*
            if (startDate.getTimee()>endDate.getEndTime()) { //判断时间戳
                return true;
            } else {
               return false;
            }*/
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 获取当前时间,日期以1970/1/1 存储
     * @auther Yue Zejian 2021/7/26
     * @return
     */
    public static Date getNowTime() {
        String str = DateUtils.getNowDate().toString();
        String time = str.split(" ")[3];
        return dateTime(HH_MM_SS,time);
    }


    /**
     * 将特定时间,日期以1970/1/1 存储
     * @auther Yue Zejian 2021/7/26
     * @return
     */
    public static Date getNowTime(Date date) {
        String str = date.toString();
        String time = str.split(" ")[3];
        return dateTime(HH_MM_SS,time);
    }

    /**
     * 在日期时间基础上增加N分钟
     * @param date 时间基础
     * @param nMinutes 增加的分钟数
     * @return
     */
    public static Date addMinutes2Date(Date date, int nMinutes){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        // 24小时制
        cal.add(Calendar.MINUTE, nMinutes);
        return cal.getTime();
    }

    public static Date getCurrentNoonTime() {
        Calendar calendar =Calendar.getInstance();
        calendar.set(1970,1,1,12,0,0);
        Date date=calendar.getTime();
        return date;
    }

    public static Date getDateByStandardString(String date){
        Date result = new Date();
        try {
            result = new SimpleDateFormat("yyyy-MM-dd").parse(date);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static Date getDateByStandardString(String date, String fromat){
        Date result = new Date();
        try {
            result = new SimpleDateFormat(fromat).parse(date);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @TODO 获取一周开始到结束的list集合
     * @param dBegin
     * @param dEnd
     * @author chai.jinwang
     * @return
     */
    public static List<Date> findDates(Date dBegin, Date dEnd)
    {
        List lDate = new ArrayList();
        lDate.add(dBegin);
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime()))
        {
            // 根据日历的规则,为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            lDate.add(calBegin.getTime());
        }
        return lDate;
    }

    public static List<Date> getTimeInterval(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        // 判断要计算的日期是否是周日,如果是则减一天计算周六的,否则会出问题,计算到下一周去了
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
        if (1 == dayWeek) {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }
        // System.out.println("要计算日期为:" + sdf.format(cal.getTime())); // 输出要计算日期
        // 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
        //cal.setFirstDayOfWeek(Calendar.MONDAY);
        // 获得当前日期是一个星期的第几天
        int day = cal.get(Calendar.DAY_OF_WEEK);
        // 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
        Date b = cal.getTime();
        cal.add(Calendar.DATE, 6);
        Date e = cal.getTime();
        List<Date> l = new ArrayList<>();
        l.add(b);
        l.add(e);
        return l;
    }

    /**
     * 当前时间向推几小时
     * @param ihour 小时
     * @return String
     * yuezejian
     */
    public static String dateRoll(int ihour) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        //(1)获取当前时间
        LocalDateTime date = LocalDateTime.now();
        //(2)获取当前时间的前几小时时间
        LocalDateTime localDateTime = date.minusHours(ihour);

        return dateTimeFormatter.format(localDateTime);
    }


    public static void main(String[] args) {
//        System.out.println(getTimeInterval(new Date()));
//        System.out.println(findDates(getTimeInterval(new Date()).get(0),getTimeInterval(new Date()).get(1)));
        System.out.println(DateUtils.dateRoll(2));
    }
}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

咖啡汪

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

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

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

打赏作者

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

抵扣说明:

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

余额充值