[Java] Time commonly used tools

Recently, I wrote a timetable system, which involved a lot of time calculation, and summarized some commonly used methods of calculating time, which is convenient for future inspection, and some methods are estimated

Possible packages to be imported

hutool toolkit, this is a very complete tool documentation, it is worth recommending

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

Get the day of the week according to the date

/**
     * 根据日期获取当天是周几
     *
     * @param datetime 日期
     * @return 周几
     */
    public static int dateToWeek(String datetime) {
    
    
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        System.out.println(cal);
        Date date;
        try {
    
    
            date = sdf.parse(datetime);
            cal.setTime(date);
        } catch (ParseException e) {
    
    
            e.printStackTrace();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        System.out.println("w为:" + w);
        return w;
    }

The offset of the date, jump to the specified week on the specified date

/**
     * 日期的偏移,在指定的日期跳到指定的周
     *
     * @param datetime
     * @param startWeek
     * @return
     */
    public static Date timeMove(String datetime, Integer startWeek) {
    
    

        Date date = DateUtil.parse(datetime);

        //常用偏移,结果:2017-03-04 22:33:23
        Date newDate2 = DateUtil.offsetDay(date, 7 * (startWeek - 1));
        return newDate2;
    }

Get the date in the first few weeks of the current time

/**
     * 获取当前时间处在第几周的日期
     * @param date 当前的时间,是从周一开始
     * @param startWeek 第几周
     * @return
     */
    public static List<String> dayListByWeek(Date date, Integer startWeek){
    
    
        List<String> dayList=new ArrayList<>();
        SimpleDateFormat sdf2= new SimpleDateFormat("dd");
        for (int i = 0; i <7 ; i++) {
    
    
            DateTime newDate2 = DateUtil.offsetDay(date, i);
            String day = sdf2.format(newDate2);
            dayList.add(day);
        }

        return dayList;
    }

Get current month

 /**
     * 得到当前月份
     * @param date
     * @return
     */
    public static String getMonth(Date date){
    
    
        SimpleDateFormat sdf= new SimpleDateFormat("MM");
        String month = sdf.format(date);
        return month;
    }

After the specified time, check the specified time by the day of the week

/**
     * 在指定时间后,通过周几来查询到指定的时间
     *
     * @param date
     * @param week
     * @return
     */
    public static Date dayMove(Date date, Integer week) {
    
    
        //常用偏移,结果:2017-03-04 22:33:23
        Date newDate2 = DateUtil.offsetDay(date, week - 1);
        return newDate2;
    }

Get the date of Monday (Tuesday, etc.) within a certain period of time

/**
     * 获取某段时间内的周一(二等等)的日期
     * @param dataBegin 开始日期
     * @param dataEnd 结束日期
     * @param weekDays 获取周几,1-6代表周一到周六。0代表周日
     * @return 返回日期List
     */
    public static List<String> getDayOfWeekWithinDateInterval(String dataBegin, String dataEnd, int weekDays) {
    
    
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<String> dateResult = new ArrayList<>();
        Calendar cal = Calendar.getInstance();
        String[] dateInterval = {
    
    dataBegin, dataEnd};
        Date[] dates = new Date[dateInterval.length];
        for (int i = 0; i < dateInterval.length; i++) {
    
    
            String[] ymd = dateInterval[i].split("[^\\d]+");
            cal.set(Integer.parseInt(ymd[0]), Integer.parseInt(ymd[1]) - 1, Integer.parseInt(ymd[2]));
            dates[i] = cal.getTime();
        }
        for (Date date = dates[0]; date.compareTo(dates[1]) <= 0; ) {
    
    
            cal.setTime(date);
            if (cal.get(Calendar.DAY_OF_WEEK) - 1 == weekDays) {
    
    
                String format = sdf.format(date);
                dateResult.add(format);
            }
            cal.add(Calendar.DATE, 1);
            date = cal.getTime();
        }
        return dateResult;
    }

This is to keep only the year, month and day after converting the time

 /**
     * 这是将时间转换后只保留年月日
     *
     * @param date
     * @return
     */
    public static String dateConversion(Date date) {
    
    
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String s = sdf.format(date); // 把带时分秒的 date 转为 yyyy-MM-dd 格式的字符串
        try {
    
    
            Date date2 = sdf.parse(s); // 把上面的字符串解析为日期类型
            String format = sdf.format(date2);
            System.out.println("这是转换后只保留年月日的时间" + format);
            return format;
        } catch (ParseException e) {
    
    
            e.printStackTrace();
        }
        return null;
    }

Convert the time of the string to Date

/**
     * 将字符串的时间转换为Date
     *
     * @param dateStr
     * @return
     */
    public static Date strToDate(String dateStr) {
    
    
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dateTime = null;
        try {
    
    
            dateTime = simpleDateFormat.parse(dateStr);
        } catch (ParseException e) {
    
    
            e.printStackTrace();
        }

        return dateTime;
    }

Convert time to timestamp

  /**
     * 将时间转为时间戳
     * @param date
     * @return
     */
    public static Long toUnixTime(Date date) {
    
    
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String t = df.format(date);
        /**
         * 获取日期转换为Unix时间戳
         */
        long epoch = 0;
        try {
    
    
            epoch = df.parse(t).getTime();
        } catch (ParseException e) {
    
    
            e.printStackTrace();
        }
        return epoch;
    }


    /**
     * 将字符时间转换为Unix时间戳,毫秒
     * @param timeStr
     * @return
     */
    public static Long jointUnixTime(String timeStr) {
    
    
        Date date = strToDate(timeStr);

        Long aLong = toUnixTime(date);
        return aLong;
    }

    /**
     * 将字符时间转换为Unix时间戳,秒
     * @param timeStr
     * @return
     */
    public static Long jointUnixTimeSec(String timeStr) {
    
    
        Date date = strToDate(timeStr);
        long time = date.getTime()/1000;
        return time;
    }

Get the week number of the day

 /**
     * 获取当天的周数
     * @param beginDateStr  开始的时间
     * @param endDateStr    结束的时间
     * @return
     */
    public static long getDaySub(String beginDateStr, String endDateStr) {
    
    
        long day = 0;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        java.util.Date beginDate;
        java.util.Date endDate;
        try {
    
    
            //先判断学期开始日期是星期几
            Calendar c = Calendar.getInstance();// 获得一个日历的实例
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            c.setTime(sdf.parse(beginDateStr));
            int dayNum[] = {
    
    6, 0, 1, 2, 3, 4, 5};//对应的星期几和星期一倒推相差几天
            //算出的星期几,和星期一差几天就把开始时间多倒推几天
            c.add(Calendar.DATE, -dayNum[c.get(Calendar.DAY_OF_WEEK) - 1]);
            beginDate = c.getTime();
            //beginDate = format.parse(beginDateStr);
            System.out.println(sdf.format(beginDate));
            endDate = format.parse(endDateStr);
            day = (endDate.getTime() - beginDate.getTime()) / (24 * 60 * 60 * 1000);
            //System.out.println("相隔的天数="+day);
        } catch (ParseException e) {
    
    
            // TODO 自动生成 catch 块
            e.printStackTrace();
        }
        return day / 7 + 1;
    }

Get a separate year, month, and day

/**
     *获取单独的 年 月 日
     * @param date  传过来的时间  例:2020-08-01
     * @return
     */
    public static String getYear(Date date){
    
    
        SimpleDateFormat sdf0 = new SimpleDateFormat("yyyy");

        SimpleDateFormat sdf1 = new SimpleDateFormat("MM");
        SimpleDateFormat sdf2= new SimpleDateFormat("dd");
        String str1 = sdf0.format(date);

        String str2 = sdf1.format(date);

        String str3 = sdf2.format(date);

        System.out.println("年份bai为:"+str1);

        System.out.println("月份为:"+str2);

        System.out.println("日为:"+str3);
        return "年"+str1+" "+"月"+" "+str2+"日"+str3;
    }

Get the day, month and year

 /**
     * 获取当天的年月日
     * @return
     */
    public static String getDay(){
    
    
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String day = df.format(new Date());

        return day;
    }
/**
     * 获取当天的星期一日期
     * @return
     */
    public static String getMondeyDate(){
    
    
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar cal = Calendar.getInstance();
        cal.setFirstDayOfWeek(Calendar.MONDAY);// 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);// 获得当前日期是一个星期的第几天
        if(dayWeek==1){
    
    
            dayWeek = 8;
        }
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - dayWeek);// 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
        Date mondayDate = cal.getTime();
        String weekBegin = sdf.format(mondayDate);
        return weekBegin;
    }

Get a few minutes in advance

 /**
     * 获取提前几分钟的时间
     * @param time
     * @return
     */
    public static String beforeTime(String time){
    
    
        String dateStr=time;
        Date date = DateUtil.parse(dateStr);
        Calendar beforeTime = Calendar.getInstance();
        beforeTime.setTime(date);

        beforeTime.add(Calendar.MINUTE, -5);// 5分钟之前的时间

        Date beforeD = beforeTime.getTime();
        String before5 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(beforeD);
        return before5;

    }

Guess you like

Origin blog.csdn.net/Black_Customer/article/details/108294211