zoukankan      html  css  js  c++  java
  • jdk8获取当前时间|时间加减|java8时间格式化|时间处理工具|时间比较|线程安全的时间处理方法

    目录

    前言

    一、jdk8与jdk7以及之前的日期和时间处理类的不同:

    二、Java 8日期/时间类

    三:日期和时间主要类的关系(待更新)

    四:日期操作和处理

    获取当前日期(只能精确到年月日)

    获取当前时间(可以精确到毫秒)

    获取上周周一的日期

    获取具体年、月、日、小时、分钟、秒

    指定日期、时间

    判断两个日期是否相等

    计算几年后(前)、几月后(前)、几天后(前)等的日期

    判断指定月份有多少天

    计算两个日期之间相差月数、天数、分钟数


    前言

    在很久之前,我总结了一些jdk7版本之前的关于时间处理的一些公共方法,日期转换成字符串、指定时间加上指定天数后的日期、获取上周周一时间 等等;具体的可以戳链接查看完整的:https://blog.csdn.net/qq_27471405/article/details/79523556

    但是这些是非线程安全的,不建议采用,举个例子

    在一个类中,有以下代码:
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public String getDate(Date date){
    return sdf.format(date);
    }

    上面这串代码在并发的时候,是线程不安全的,具体的如何不安全,大家可以搜一下,这里不多讲了

    那么今天给大家分享的是jdk8之后的一些时间处理的公共方法,是线程安全的,理应大家以后应该用下面这些方法

    一、jdk8与jdk7以及之前的日期和时间处理类的不同:


    1. Java的java.util.Date和java.util.Calendar类易用性差,不支持时区,并且是可变的,也就意味着他们都不是线程安全的;
    2. 用于格式化日期的类DateFormat被放在java.text包中,它是一个抽象类,所以我们需要实例化一个SimpleDateFormat对象来处理日期格式化,并且DateFormat也是非线程安全,这意味着如果你在多线程程序中调用同一个DateFormat对象,会得到意想不到的结果。
    3. 对日期的计算方式繁琐,而且容易出错,因为月份是从0开始的,这意味着从Calendar中获取的月份需要加一才能表示当前月份
    由于以上这些问题,出现了一些三方的日期处理框架,例如Joda-Time,data4j等开源项目


    二、Java 8日期/时间类


    Java 8的日期和时间类包含LocalDate、LocalTime、Instant、Duration以及Period,这些类都包含在java.time包中。

    • Instant:瞬时实例。

    • LocalDate:本地日期,不包含具体时间 例如:2014-01-14 可以用来记录生日、纪念日、加盟日等。

    • LocalTime:本地时间,不包含日期。

    • LocalDateTime:组合了日期和时间,但不包含时差和时区信息。

    • ZonedDateTime:最完整的日期时间,包含时区和相对UTC或格林威治的时差。

    新API还引入了 ZoneOffSet 和 ZoneId 类,使得解决时区问题更为简便。解析、格式化时间的 DateTimeFormatter 类也全部重新设计。

    三:日期和时间主要类的关系(待更新)

    1 、LocalDate的关系图:

    2、 LocalTime:

    3 、LocalDateTime:

    4 、OffsetTime:

    5 、OffsetDateTime:

    6、 ZonedDateTime:

    7 、Instant:

    四:日期操作和处理

    获取当前日期(只能精确到年月日)

    /**
         * 获取当前日期(只能精确到年月日)
         * @param formatStr
         */
        public static void getNowDate(String formatStr){
            if (StringUtils.isBlank(formatStr)){
                formatStr = "yyyy-MM-dd";
            }
            LocalDate now = LocalDate.now();
            System.out.println("当前日期: " + now + " " + now.getDayOfWeek());
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatStr);                        // * 原文章链接:https://blog.csdn.net/qq_27471405/article/details/106824023   * 其他均为盗版,公众号:灵儿的笔记(zygxsq)
            String nowFormat = now.format(dateTimeFormatter);
            System.out.println("格式化后的当前日期:"+nowFormat);
        }

    如果传格式化到天小时秒的话,会报异常:Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: HourOfDay

    获取当前时间(可以精确到毫秒)

     /**
         * 获取当前时间(可以精确到毫秒)
         * 原文章链接:https://blog.csdn.net/qq_27471405/article/details/106824023
         * 其他均为盗版,公众号:灵儿的笔记(zygxsq)
         * @param formatStr
         */
        public static void getNowTime(String formatStr){
            if (StringUtils.isBlank(formatStr)){
                formatStr = "yyyy-MM-dd";
            }
            LocalDateTime now = LocalDateTime.now();
            System.out.println("当前日期: " + now + " " + now.getDayOfWeek());
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatStr);                      // * 原文章链接:https://blog.csdn.net/qq_27471405/article/details/106824023    * 其他均为盗版,公众号:灵儿的笔记(zygxsq)
    
            String nowFormat = now.format(dateTimeFormatter);
            System.out.println("格式化后的当前日期:"+nowFormat);
    
        }

    获取上周周一的日期

    /**
         * 获取上周周一的日期
         * 原文章链接:https://blog.csdn.net/qq_27471405/article/details/106824023
         * 其他均为盗版,公众号:灵儿的笔记(zygxsq)
         */
        public static void getLastMonday(){
            LocalDate now = LocalDate.now();
            System.out.println("当前日期: " + now + " " + now.getDayOfWeek());
            LocalDate todayOfLastWeek = now.minusDays(7);
            LocalDate last_monday = todayOfLastWeek.with(TemporalAdjusters.previous(DayOfWeek.SUNDAY)).plusDays(1); // * 原文章链接:https://blog.csdn.net/qq_27471405/article/details/106824023   * 其他均为盗版,公众号:灵儿的笔记(zygxsq)
            System.out.println("上周周一日期:"+last_monday); 
        }

    获取具体年、月、日、小时、分钟、秒

    /**
         * 获取具体年、月、日、小时、分钟、秒
         * @param formatStr
         */
        public static void getDetailTime(String formatStr){
            LocalDateTime now = LocalDateTime.now();
            System.out.println("当前日期: " + now + " " + now.getDayOfWeek());
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatStr);
    
            String nowFormat = now.format(dateTimeFormatter);
            System.out.println("格式化后的当前日期:"+nowFormat);
    
            int year = now.getYear();
            int month = now.getMonthValue();
            int day = now.getDayOfMonth();
            int hour = now.getHour();
            int minute = now.getMinute();
            int second = now.getSecond();
            int nano = now.getNano();
            
            System.out.printf("年 : %d  月 : %d  日 : %d  小时:%d 分钟:%d 秒:%d  毫秒:%d %n", year, month, day,hour,minute,second,nano);  // * 原文章链接:https://blog.csdn.net/qq_27471405/article/details/106824023   * 其他均为盗版,公众号:灵儿的笔记(zygxsq)
        }

    指定日期、时间

    /**
         * 指定日期、时间
         * 原文章链接:https://blog.csdn.net/qq_27471405/article/details/106824023
         * 其他均为盗版,公众号:灵儿的笔记(zygxsq)
         * @param formatStr
         */
        public static void createTime(String formatStr){
            LocalDate date = LocalDate.of(2020, 04, 27);
            System.out.println("指定日期: " + date);
            LocalDateTime time = LocalDateTime.of(2020, 04, 27,06,10,50);
            System.out.println("指定时间: " + time);
    
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatStr);
            String nowFormat = time.format(dateTimeFormatter);
            System.out.println("格式化后的指定时间:"+nowFormat);
        }

    判断两个日期是否相等

    /**
         * 判断两个日期是否相等、之前、之后
         * 原文章链接:https://blog.csdn.net/qq_27471405/article/details/106824023
         * 其他均为盗版,公众号:灵儿的笔记(zygxsq)
         */
        public static void compareDate(){
            LocalDate now = LocalDate.now();
            System.out.println("当前时间: " + now + " " + now.getDayOfWeek());
            LocalDate date1 = LocalDate.of(2020, 04, 27);
            LocalDate date2 = LocalDate.of(2020, 04, 27);
            LocalDate date3 = LocalDate.of(2020, 04, 28);
    
            boolean equal = now.isEqual(date1);
            System.out.printf("是否是同一时间:%s ", date1.equals(now));
            System.out.printf("是否是同一时间:%s ", now.isEqual(date1));
    
            System.out.println();
            System.out.printf("是否是同一时间:%s ", date1.equals(date2));
            System.out.printf("是否是同一时间:%s ", date1.isEqual(date2));
            System.out.println();
            System.out.println("data2(2020.4.27)是否比data3(2020.4.28)小: "+date2.isBefore(date3));             * 原文章链接:https://blog.csdn.net/qq_27471405/article/details/106824023   * 其他均为盗版,公众号:灵儿的笔记(zygxsq)
            System.out.println("data2(2020.4.27)是否比data3(2020.4.28)大: "+date2.isAfter(date3));
        }

    计算几年后(前)、几月后(前)、几天后(前)等的日期

    /**
         * 计算几年后(前)、几月后(前)、几天后(前)等的日期
         * 原文章链接:https://blog.csdn.net/qq_27471405/article/details/106824023
         * 其他均为盗版,公众号:灵儿的笔记(zygxsq)
         * @param formatStr
         */
        public static void calculateTime(String formatStr){
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime newTime = now.plusHours(6);
    
            System.out.println("当前时间: " + now + " " + now.getDayOfWeek());
            System.out.println("6小时后的时间: " +  newTime);
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatStr);
            String nowFormat = now.format(dateTimeFormatter);
            String newFormat = newTime.format(dateTimeFormatter);
            System.out.println("格式化后的当前时间:"+nowFormat);
            System.out.println("格式化后的6小时后的时间:"+newFormat);
    
            LocalDateTime twoYearsLater = now.plusYears(2);
            String twoYearsFormat = twoYearsLater.format(dateTimeFormatter);
            System.out.println("2年后的时间:"+twoYearsFormat);
    
            LocalDateTime twoMonthsLater = now.plusMonths(2);
            String twoMonthsFormat = twoMonthsLater.format(dateTimeFormatter);
            System.out.println("2个月后的时间:"+twoMonthsFormat);
    
            LocalDateTime twoWeeksLater = now.plusWeeks(2);
            String twoWeeksFormat = twoWeeksLater.format(dateTimeFormatter);
            System.out.println("2周后的时间:"+twoWeeksFormat);
    
            LocalDateTime twoDaysLater = now.plusDays(2);
            String twoDaysFormat = twoDaysLater.format(dateTimeFormatter);
            System.out.println("2天后的时间:"+twoDaysFormat);
    
            LocalDateTime twoMinutesLater = now.plusMinutes(2);
            String twoMinutesFormat = twoMinutesLater.format(dateTimeFormatter);
            System.out.println("2分钟后的时间:"+twoMinutesFormat);
    
            LocalDateTime twoMinutesBefore = now.plusMinutes(-2);
            String twoMinutesBeforeFormat = twoMinutesBefore.format(dateTimeFormatter);
            System.out.println("2分钟前的时间:"+twoMinutesBeforeFormat);
    
            //原文章链接:https://blog.csdn.net/qq_27471405/article/details/106824023
            //其他均为盗版,公众号:灵儿的笔记(zygxsq)
            //还可以直接通过plus方法计算 几年(月周天)后
            LocalDateTime twoYearsPlusLater = now.plus(2, ChronoUnit.YEARS);
            String twoYearsPlusLaterFormat = twoYearsPlusLater.format(dateTimeFormatter);
            System.out.println("2年后的时间:"+twoYearsPlusLaterFormat);
    
            //负号表示 之前
            LocalDateTime twoDaysPlusBefore = now.plus(-2, ChronoUnit.DAYS);
            String twoDaysPlusBeforeFormat = twoDaysPlusBefore.format(dateTimeFormatter);
            System.out.println("2天前的时间:"+twoDaysPlusBeforeFormat);
            //也可以用minus,也表示之前
            LocalDateTime twoDaysMinusBefore = now.minus(2, ChronoUnit.DAYS);
            String twoDaysMinusBeforeFormat = twoDaysMinusBefore.format(dateTimeFormatter);
            System.out.println("2天前的时间:"+twoDaysMinusBeforeFormat);
        }

    判断指定月份有多少天

     /**
         * 判断指定月份有多少天
         */
        public static void getMonthDays(){
            YearMonth currentYearMonth = YearMonth.now();
            System.out.println("当前时间:"+currentYearMonth);
            System.out.println("当前月份有多少天:"+currentYearMonth.lengthOfMonth());
    
            YearMonth february = YearMonth.of(2020, Month.FEBRUARY);
            System.out.println("指定时间的月份2月:"+february);
            System.out.println("指定时间的月份2月有多少天:"+february.lengthOfMonth());
            
        }

    计算两个日期之间相差月数、天数、分钟数

    /**
         * 计算两个日期之间相差月数、天数、分钟数
         * 原文章链接:https://blog.csdn.net/qq_27471405/article/details/106824023
         * 其他均为盗版,公众号:灵儿的笔记(zygxsq)
         */
        public static void getDaysBetweenTwoDate(){
            LocalDate startDate = LocalDate.of(2020, 04, 27);
            LocalDate endDate = LocalDate.of(2020, 07, 2);
    
            long months = startDate.until(endDate, ChronoUnit.MONTHS);
            long days = startDate.until(endDate, ChronoUnit.DAYS);
            System.out.println("startDate(2020.04.27)和endDate(2020.07.02)相差月数:"+months);
            System.out.println("startDate(2020.04.27)和endDate(2020.07.02)相差天数:"+days);
    
            LocalDateTime startTime = LocalDateTime.of(2020, 04, 27,18,20,10);
            LocalDateTime endTime = LocalDateTime.of(2020, 04, 27,18,30,12);
            long minutes = startTime.until(endTime, ChronoUnit.MINUTES);
            System.out.println("startTime(2020.04.27 18:20:10)和endTime(2020.04.27 18:30:20)相差分钟数:"+minutes); // * 原文章链接https://blog.csdn.net/qq_27471405/article/details/106824023 * 其他均为盗版,公众号:灵儿的笔记(zygxsq)
    
        }


    参考文章 

    https://blog.csdn.net/u012091080/article/details/79901830

    https://blog.csdn.net/chenleixing/article/details/44408875

    https://blog.csdn.net/feicongcong/article/details/78224494

    感谢原作者的分享,让技术人能够更快的解决问题 

    我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=lnlh8qa6e7an

  • 相关阅读:
    dotnet 实现 RedioButton 单选问题 该名称问题
    max 中对map 通道的拷贝 (首先要具有多通道)
    python的数组操作
    sshkeygen命令打通主机之间的ssh
    如何搭建个人的yum repository
    不错的博客
    测试 ListView 的效率 3 [原创]
    Sending SMS on Android and tracking it
    j2se 网络之 URLConnection
    如何实现自定菜单
  • 原文地址:https://www.cnblogs.com/jalenFish/p/14099001.html
Copyright © 2011-2022 走看看