jdk8获取当前时间|时间加减|java8时间格式化|时间处理工具|时间比较|线程安全的时间处理方法

简介: jdk8获取当前时间|时间加减|java8时间格式化|时间处理工具|时间比较|线程安全的时间处理方法

前言

在很久之前,我总结了一些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)
    }

目录
打赏
0
0
0
0
2
分享
相关文章
6个Java 工具,轻松分析定位 JVM 问题 !
本文介绍了如何使用 JDK 自带工具查看和分析 JVM 的运行情况。通过编写一段测试代码(启动 10 个死循环线程,分配大量内存),结合常用工具如 `jps`、`jinfo`、`jstat`、`jstack`、`jvisualvm` 和 `jcmd` 等,详细展示了 JVM 参数配置、内存使用、线程状态及 GC 情况的监控方法。同时指出了一些常见问题,例如参数设置错误导致的内存异常,并通过实例说明了如何排查和解决。最后附上了官方文档链接,方便进一步学习。
252 4
银行转账虚拟生成器app,银行卡转账截图制作软件,java实现截图生成工具【仅供装逼娱乐用途】
本内容提供Java生成自定义图片的示例代码,涵盖基础图像创建、文本添加及保存功能,适合学习2D图形编程。包括教学示例图片生成、文本图层处理和数字水印技术实现方案。
|
23天前
|
JD-GUI,java反编译工具及原理: JavaDecompiler一个Java反编译器
Java Decompiler (JD-GUI) 是一款由 Pavel Kouznetsov 开发的图形化 Java 反编译工具,支持 Windows、Linux 和 Mac Os。它能将 `.class` 文件反编译为 Java 源代码,支持多文件标签浏览、高亮显示,并兼容 Java 5 及以上版本。JD-GUI 支持对整个 Jar 文件进行反编译,可跳转源码,适用于多种 JDK 和编译器。其原理基于将字节码转换为抽象语法树 (AST),再通过反编译生成代码。尽管程序可能带来安全风险,但可通过代码混淆降低可读性。最新版修复了多项识别错误并优化了内存管理。
375 1
银行转账虚拟生成器app,银行卡转账截图制作软件,java实现截图生成工具【仅供装逼娱乐用途】
本项目提供了一套基于Java的图片处理教学方案,包含自定义图片生成、图像水印添加及合法电子凭证生成技术示例。
【高薪程序员必看】万字长文拆解Java并发编程!(9-2):并发工具-线程池
🌟 ​大家好,我是摘星!​ 🌟今天为大家带来的是并发编程中的强力并发工具-线程池,废话不多说让我们直接开始。
90 0
|
8月前
|
java小工具util系列5:java文件相关操作工具,包括读取服务器路径下文件,删除文件及子文件,删除文件夹等方法
java小工具util系列5:java文件相关操作工具,包括读取服务器路径下文件,删除文件及子文件,删除文件夹等方法
173 9
FastExcel:开源的 JAVA 解析 Excel 工具,集成 AI 通过自然语言处理 Excel 文件,完全兼容 EasyExcel
FastExcel 是一款基于 Java 的高性能 Excel 处理工具,专注于优化大规模数据处理,提供简洁易用的 API 和流式操作能力,支持从 EasyExcel 无缝迁移。
1433 65
FastExcel:开源的 JAVA 解析 Excel 工具,集成 AI 通过自然语言处理 Excel 文件,完全兼容 EasyExcel
Java开发现在比较缺少什么工具?
【10月更文挑战第15天】Java开发现在比较缺少什么工具?
85 1
|
8月前
|
java小工具util系列2:字符串工具
java小工具util系列2:字符串工具
224 83
JDK 10中的局部变量类型推断:Java编程的简化与革新
JDK 10引入的局部变量类型推断通过`var`关键字简化了代码编写,提高了可读性。编译器根据初始化表达式自动推断变量类型,减少了冗长的类型声明。虽然带来了诸多优点,但也有一些限制,如只能用于局部变量声明,并需立即初始化。这一特性使Java更接近动态类型语言,增强了灵活性和易用性。
174 53
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等

登录插画

登录以查看您的控制台资源

管理云资源
状态一览
快捷访问