总结Java常用的时间相关转化

时间:2022-09-24 07:50:14

Java常用的时间相关转化

下面代码的一些变量基本解释说明
datePattern:时间对应的字符串格式
date: 时间
dateStr:字符串格式的时间
指定的几个常量:

?
1
2
3
public static final long DAYTIMESTAMP = 24 * 60 * 60 * 1000L;
public static final  String SHORTDATEFORMATER = "yyyy-MM-dd";
public static final  String LONGDATEFORMATER = "yyyy-MM-dd HH:mm:ss";

1.时间转化为指定格式的字符串

?
1
2
3
4
5
6
7
8
public static final String convertDateToString(String datePattern, Date date) {
        String returnValue = null;
        if (date != null) {
            SimpleDateFormat df = new SimpleDateFormat(datePattern);
            returnValue = df.format(date);
        }
        return (returnValue);
    }

2.指定格式的字符串转时间

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static final Date convertStringToDate(String datePattern,String dateStr) {
        if( StringUtils.isBlank(dateStr) ){
            return null;
        }
        SimpleDateFormat df = null;
        Date date = null;
        df = new SimpleDateFormat(datePattern);
        try {
            date = df.parse(dateStr);
        } catch (ParseException pe) {
            log.error("异常![{}]",pe);
            return null;
        }
        return (date);
    }

3.判断日期是否未过期

?
1
2
3
4
5
6
7
public static final boolean isNonExpired(Date date){
        Calendar calendarNow = Calendar.getInstance();
        calendarNow.setTime(calendarNow.getTime());
        Calendar calendarGiven = Calendar.getInstance();
        calendarGiven.setTime(date);
        return calendarNow.before(calendarGiven);
    }

4.判断日期是否过期

?
1
2
3
4
5
6
7
public static final boolean isExpired(Date date){
        Calendar calendarNow = Calendar.getInstance();
        calendarNow.setTime(calendarNow.getTime());
        Calendar calendarGiven = Calendar.getInstance();
        calendarGiven.setTime(date);
        return calendarNow.after(calendarGiven);
    }

5.判断两个日期大小

?
1
2
3
public static final int compare( Date firstDate,Date secondDate ){
        return firstDate.compareTo(secondDate);
    }

备注:如果第一个日期参数大于第二个日期返回 1;如果两个日期相等返回0;如果第一个日期小于第二个日期 返回-1

6.获取指定时间前n个月的时间

?
1
2
3
4
5
6
public static Date DateMinus(Date date,int month){
          Calendar calendar = Calendar.getInstance();
          calendar.setTime(date);
          calendar.add(Calendar.MONTH, -month);
        return calendar.getTime();
    }

7.获取指定日期之前指定天,包含传入的那一天

?
1
2
3
4
public static String getDaysBefore(Date date, int days) {
        Date td = new Date(date.getTime() - DAYTIMESTAMP * days);
        return DateUtils.convertDateToString(SHORTDATEFORMATER, td);
    }

8.获取指定日期之前指定天的数组,包含传入的那一天

?
1
2
3
4
5
6
7
public static List<String> getDaysBeforeArray(Date date, int days){
        List<String> resultList = new ArrayList<>();
        for (int i = days-1; i >= 0; i--) {
            resultList.add(getDaysBefore(date, i));
        }
        return resultList;
    }

备注:配合第七条使用

9.获取指定时间的0点

?
1
2
3
4
5
6
7
8
public static Date getDayStartTimeByDate(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTime();
    }

10.获取指定日期的最后一秒

?
1
2
3
4
5
6
7
8
public static Date getDayEndOfDay(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        return calendar.getTime();
    }

11.获取当时时间前一个小时时间

?
1
2
3
4
5
public static Date getDayBeforeHour(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY,calendar.get(Calendar.HOUR_OF_DAY)-1);
        return calendar.getTime();
    }

12.获取两个时间之间相差的分钟数

?
1
2
3
4
5
6
public static String getdifferMinute(Date endDate, Date nowDate){
        long nm = 1000 * 60;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        return String.valueOf(diff/nm);
    }

备注:endDate 相对大的时间;nowDate 相对小的时间;可以在入参的时候就判断好,或者可以在方法内优化,即调用第五条操作根据返回值进行操作就可以。

13.获取两个时间之间间隔多少天

?
1
2
3
public static int differentDaysByMillisecond(Date date1,Date date2){
        return (int) ((date2.getTime() - date1.getTime()) / (1000*3600*24));
    }

14.获取两个时间之间的日期集合

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public static List<Date> getDatesBetweenTwoDate(Date beginDate, Date endDate ) {
        List<Date> dates = new ArrayList<>();
        try{
            dates.add(beginDate);// 把开始时间加入集合
            Calendar cal = Calendar.getInstance();
            // 使用给定的 Date 设置此 Calendar 的时间
            cal.setTime(beginDate);
            while (true) {
                // 根据日历的规则,为给定的日历字段添加或减去指定的时间量
                cal.add(Calendar.DAY_OF_MONTH, 1);
                // 测试此日期是否在指定日期之后
                if (endDate.after(cal.getTime())) {
                    dates.add(cal.getTime());
                } else {
                    break;
                }
            }
            dates.add(endDate);// 把结束时间加入集合
        }catch(Exception e){
            log.error("获取时间集合异常");
        }
 
        return dates;
    }

15.获取当月月初第一天

?
1
2
3
4
5
6
7
public static String getMonthFirstDay() {
        SimpleDateFormat format = new SimpleDateFormat(SHORTDATEFORMATER);
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天
        return format.format(c.getTime());
    }

16.时间戳格式化

?
1
2
3
4
5
6
7
8
9
public static String parseDate(Long timeStamp){
        String resDate = "";
        if(null != timeStamp){
            Date date = new Date(timeStamp);
            SimpleDateFormat smf = new SimpleDateFormat(LONGDATEFORMATER);
            resDate= smf.format(date);
        }
        return resDate;
    }

17.获取今天是当前年第n周

?
1
2
3
4
5
6
7
8
9
10
11
12
13
public static int getWeekOfYear(String dateStr,int startCalendar){
        SimpleDateFormat format = new SimpleDateFormat(SHORTDATEFORMATER);
        Calendar calendar = Calendar.getInstance();
        try {
            Date date = format.parse(dateStr);
            calendar.setFirstDayOfWeek(startCalendar);
            calendar.setTime(date);
        }
        catch (Exception error) {
            error.printStackTrace();
        }
        return calendar.get(Calendar.WEEK_OF_YEAR);
    }

备注:startCalendar是指从周几作为本周的开始周期 例:以周五作为一周的开始则startCalendar传值为Calendar.FRIDAY

总结:目前常用到的时间相关的操作大概就是这些,其中一些没有覆盖到的可以通过上面相关操作调整就能得到,如有遗漏请在评论中补充,我及时调整增加。

到此这篇关于总结Java常用的时间相关转化的文章就介绍到这了,更多相关Java时间相关转化内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/weixin_42127766/article/details/117922566