目录
JDK8 新增的日期时间类
在本人之前的博文《处理时间的类 —— System类、Date类 、SimpleDateFormat类 与 Calendar类》中,讲到过表示时间的类,有三类:Date、SimpleDateFormat、Calendar类(System.currentTimeMillis()勉强也能算作是一个)
那么,在JDK8的时代,Java提供了几个新的、线程安全的、用于处理时间的类。
现在,本人就来讲讲这几个类:
@
首先是 LocalDate、LocalTime、LocalDateTime类:
LocalDate、LocalTime、LocalDateTime类:
概述:
这三个类分别表示使用 ISO-8601日历系统的 日期、时间、日期和时间
它们提供了简单的日期或时间,并不包含 当前的时间 信息。
也不包含 与时区相关 的信息。
注: ISO-8601日历系统 是 国际标准化组织制定的现代公民的日期和时间的表示法
这些新增的日期时间API都在 java.time包下
获取对象的方法:
获取对象的方法:
- 通过静态方法 :now()(获取的时间是系统当前的时间)
- 通过静态方法:of()(方法参数可以指定时间)
那么,现在,本人来通过代码来展示下如何去 获取对象:
package edu.youzg.about_new_features.core.about_jdk8.core;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class Test {
    public static void main(String[] args) {
        /* 通过静态方法 now() 返回该类的实例 */
        //获取当前的日期时分秒
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);
        //获取当前的日期
        LocalDate now1 = LocalDate.now();
        System.out.println(now1);
        //获取当前的时分秒
        LocalTime now2 = LocalTime.now();
        System.out.println(now2);
        System.out.println("=========================================");
        /* 静态方法 of() 返回该类的实例 */
        //指定日期时分秒
        LocalDateTime localDateTime = LocalDateTime.of(2048, 11, 25, 12, 00, 30);
        System.out.println(localDateTime);
        //指定日期
        LocalDate date = LocalDate.of(2020, 12, 12);
        System.out.println(date);
        
        //指定时分秒
        LocalTime time = LocalTime.of(14, 20, 30);
        System.out.println(time);
    }
}
那么,现在,本人来展示下运行结果:
常用方法:
与获取相关的方法(get系类的方法):
- getYear():
获取年- ldt.getHour():
获取小时- getMinute():
获取分钟- getSecond():
获取秒值- getDayOfMonth():
获得月份天数(1-31)- getDayOfYear():
获得年份天数(1-366)- getDayOfWeek():
获得星期几(返回一个 DayOfWeek枚举值)- getMonth():
获得月份(返回一个 Month 枚举值)- getMonthValue():
获得月份(1-12)- getYear():
获得年份
那么,现在,本人来通过代码来展示下与获取相关的方法 的使用:
package edu.youzg.about_new_features.core.about_jdk8.core;
import java.time.LocalDateTime;
import java.time.Month;
public class Test {
    public static void main(String[] args) {
        //获取日期时分秒
        LocalDateTime now = LocalDateTime.now();
        //获取年份
        int year = now.getYear();
        System.out.println(year);
        //获取月份枚举
        //Month 枚举类,定义了十二个月份
        Month month = now.getMonth();
        System.out.println(month);
        //获取月份的数值
        int monthValue = now.getMonthValue();
        System.out.println(monthValue);
        //获取当天在本月的第几天
        int dayOfMonth = now.getDayOfMonth();
        System.out.println(dayOfMonth);
        //获取小时
        int hour = now.getHour();
        System.out.println(hour);
        //获取分钟
        int minute = now.getMinute();
        System.out.println(minute);
        //获取秒值
        int second = now.getSecond();
        System.out.println(second);
    }
}
那么,现在,本人来展示下运行结果:
格式化日期日期字符串的方法:
- format():
格式化字符串
那么,现在,本人来通过代码来展示下如何去 格式化日期日期字符串:
package edu.youzg.about_new_features.core.about_jdk8.core;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Test {
    public static void main(String[] args) {
        //获取当前日期时分秒
        LocalDateTime now = LocalDateTime.now();
        //默认格式  年-月-日T时:分:秒
        System.out.println(now);
        //指定格式
        DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyy年MM月DD日 HH时mm分ss秒");
        //传入格式
        String dateStr = now.format(ofPattern);
        System.out.println(dateStr);
    }
}
那么,现在,本人来展示下运行结果:

转换的方法:
- toLocalDate():
将目标LocalDateTime转换为相应的LocalDate对象- toLocalTime():
将目标LocalDateTime转换为相应的LocalTime对象
那么,现在,本人来通过代码来展示下如何去 转换:
package edu.youzg.about_new_features.core.about_jdk8.core;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class Test {
    public static void main(String[] args) {
        //获取当前年月日,时分秒
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now);
        //将目标LocalDateTime转换为相应的LocalDate对象
        LocalDate localDate = now.toLocalDate();
        System.out.println(localDate);
        ///将目标LocalDateTime转换为相应的LocalTime对象
        LocalTime localTime = now.toLocalTime();
        System.out.println(localTime);
    }
}
那么,现在,本人来展示下运行结果:
判断的方法:
- isAfter():
判断一个日期是否在指定日期之后- isBefore():
判断一个日期是否在指定日期之前- isEqual():
判断两个日期是否相同- isLeapYear():
判断是否是闰年(注意是LocalDate类 和 LocalDateTime类特有的方法)
那么,现在,本人来通过代码来展示下这些API的使用:
package edu.youzg.about_new_features.core.about_jdk8.core;
import java.time.LocalDate;
public class Test {
    public static void main(String[] args) {
        //获取当前的日期
        LocalDate now = LocalDate.now();
        //指定的日期
        LocalDate of = LocalDate.of(2015, 12, 12);
        //判断一个日期是否在另一个日期之前
        boolean before = of.isBefore(now);
        System.out.println(before);
        //判断一个日期是否在另一个日期之后
        boolean after = of.isAfter(now);
        System.out.println(after);
        //判断这两个日期是否相等
        boolean after1 = now.equals(of);
        System.out.println(after1);
        //判断闰年
        boolean leapYear = of.isLeapYear();
        System.out.println(leapYear);
    }
}
那么,现在,本人来展示下运行结果:
解析字符串的方法:
- paser(String str):
将一个日期字符串解析成日期对象,注意字符串日期的写法的格式要正确,否则解析失败- paser(String str, DateTimeFormatter formatter):
将字符串按照参数传入的格式进行解析
那么,现在,本人来通过代码来展示下如何去 解析字符串:
package edu.youzg.about_new_features.core.about_jdk8.core;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class Test {
    public static void main(String[] args) {
        //给出一个符合默认格式要求的日期字符串
        String dateStr="2020-01-01";
        //把日期字符串解析成日期对象 如果日期字符串时年月日 解析时用  LocalDate
        LocalDate parse = LocalDate.parse(dateStr);
        System.out.println(parse);
        System.out.println("===========================================");
        //给出一个符合默认格式要求的 时分秒 字符串
        String dateTimeStr="14:20:30";
        //把 时分秒 字符串解析成时分秒对象
        LocalTime parse1 = LocalTime.parse(dateTimeStr);
        System.out.println(parse1);
        System.out.println("=========================================");
        //给出一个符合默认格式要求的 日期时分秒 字符串
        String str="2018-12-12T14:20:30";
        //把 日期时分秒 字符串解析成时分秒对象
        LocalDateTime parse2 = LocalDateTime.parse(str);
        System.out.println(parse2);
        System.out.println("========================================");
        //给出一个自定义日期时分秒格式字符串
        String dateStr2="2020年12月12日 12:13:14";
        //给出一个自定义解析格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
        //按照指定的格式去解析
        LocalDateTime parse3 = LocalDateTime.parse(dateStr2,formatter);
        System.out.println(parse3);
    }
}
那么,现在,本人来展示下运行结果:
增减年月日时分秒的方法(plus/minus系列的方法):
- plusYears(int offset):
增加指定年份- plusMonths(int offset):
增加指定月份- plusWeeks(int offset):
增加指定周- plusDates(int offset):
增加指定日- plusHours(int offset):
增加指定时- plusMinuets(int offset):
增加指定分- plusSeconds(int offset):
增加指定秒- plusNanos(int offset):
增加指定纳秒
---- minusYears(int offset):
减少指定年- minusMonths(int offset):
减少指定月- minusWeeks(int offset):
减少指定周- minusDates(int offset):
减少指定日- minusHours(int offset):
减少指定时- minusMinuets(int offset):
减少指定分- minusSeconds(int offset):
减少指定秒- minusNanos(int offset):
减少指定纳秒
那么,现在,本人来通过代码来展示下部分API的使用:
package edu.youzg.about_new_features.core.about_jdk8.core;
import java.time.LocalDate;
import java.time.LocalDateTime;
public class Test {
    public static void main(String[] args) {
        //增加时间量的方法 plusXXX系类的方法 返回的是一个新的日期对象
        LocalDateTime now = LocalDateTime.now();
        //可以给当前的日期增加时间量
        LocalDateTime newDate= now.plusYears(1);
        int year = newDate.getYear();
        System.out.println(year);
        System.out.println("================================");
        //减去时间量的方法minusXXX 系列的方法 返回的是一个新的日期对象
        LocalDate now1 = LocalDate.now();
        LocalDate newDate2 = now1.minusDays(10);
        int dayOfMonth = newDate2.getDayOfMonth();
        System.out.println(dayOfMonth);
    }
}
那么,现在,本人来展示下运行结果:
指定年月日时分秒的方法:
- with(TemporalAdjuster adjuster):
指定特殊时间- withYear(int year):
指定年- withDayOfYear(int dayOfYear):
指定日- withMonth(int month):
指定月- withDayOfMonth(int dayOfMonth):
指定日
那么,现在,本人来通过代码来展示下部分API的使用:
package edu.youzg.about_new_features.core.about_jdk8.core;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
public class Test {
    public static void main(String[] args) {
        //指定某个日期的方法 with()方法
        LocalDate now2 = LocalDate.now();
        LocalDate localDate = now2.withYear(2014);
        System.out.println(localDate);
        // TemporalAdjusters工具类,提供了一些获取特殊日期的方法
        LocalDate with = now2.with(TemporalAdjusters.firstDayOfMonth());
        System.out.println(with);
        LocalDate with1 = now2.with(TemporalAdjusters.firstDayOfNextMonth());
        System.out.println(with1);
        //获取这个月的第几个星期几是几号,比如 TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.FRIDAY)
        // 代表的意思是这个月的第二个星期五是几号
        LocalDate with2 = now2.with(TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.FRIDAY));
        System.out.println(with2);
    }
}
那么,现在,本人来展示下运行结果:
在上文中,本人运用到了TemporalAdjuster接口,
那么,现在,本人就来讲解下这个接口:
TemporalAdjuster接口 —— 时间校正器:
概述:
一般我们用该接口的一个对应的工具类 TemporalAdjusters中的一些常量,
来指定日期
对于这个接口,我们主要运用它的几个常量 和 next()方法来指定日期
或者采用自定义的方式来指定日期
现在,本人来通过一段代码来展示下这个接口的使用:
package edu.youzg.about_new_features.core.about_jdk8.core;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
public class Test {
    public static void main(String[] args) {
        LocalDate now = LocalDate.now();
        //指定日期
        //对于一些特殊的日期,可以通过一个工具类TemporalAdjusters 来指定
        TemporalAdjuster temporalAdjuster = TemporalAdjusters.firstDayOfMonth();    //见名知意,本月第一天
        LocalDate with = now.with(temporalAdjuster);
        System.out.println(with);
        TemporalAdjuster next = TemporalAdjusters.next(DayOfWeek.SUNDAY);   //下周周末
        LocalDate with1 = now.with(next);
        System.out.println(with1);
        System.out.println("===================================");
        LocalDate now1 = LocalDate.now();
        //自定义日期 —— 下一个工作日
        LocalDate with2 = now1.with(new TemporalAdjuster() {
            @Override
            //参数 nowDate 当前的日期对象
            public Temporal adjustInto(Temporal nowDate) {
                //向下转型
                LocalDate date= (LocalDate) nowDate;
                if(date.getDayOfWeek().equals(DayOfWeek.FRIDAY)){
                    LocalDate localDate = date.plusDays(3);
                    return localDate;
                }else if(date.getDayOfWeek().equals(DayOfWeek.SATURDAY)){
                    LocalDate localDate = date.plusDays(2);
                    return localDate;
                }else{
                    LocalDate localDate = date.plusDays(1);
                    return localDate;
                }
            }
        });
        System.out.println("下一个工作日是:" + with2);
    }
}
那么,现在,本人来展示下运行结果:
Instant 时间戳类:
获取对象的方法:
now():
注意默认获取出来的是当前的美国时间,
和我们相差八个小时(因为我们在东八时区)设置偏移量的方法:
atOffset():获取系统默认时区时间的方法:
atZone():
方法的参数是要一个时区的编号(可以通过时区编号类获取ZonedDateTime类的对象)get系列的方法:
- getEpochSecond():
获取从1970-01-01 00:00:00到当前时间的秒值- toEpochMilli():
获取从1970-01-01 00:00:00到当前时间的毫秒值- getNano():
把获取到的当前时间的秒数 换算成纳秒ofEpoch系列方法:
- ofEpochSecond():
给计算机元年增加秒数- ofEpochMilli():
给计算机元年增加毫秒数
现在,本人来展示下这些API的使用:
package edu.youzg.about_new_features.core.about_jdk8.core;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Date;
public class Test {
    public static void main(String[] args) {
        //  Instant 时间戳类从1970 -01 - 01 00:00:00 截止到当前时间的毫秒值
        Instant now = Instant.now();
        System.out.println(now); //获取的是默认时区,获取的不是中国 的时区
        //获取当前时区的,我们可以添加偏移量,返回偏移过后的日期
        OffsetDateTime offsetDateTime = now.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime);
        System.out.println("===========================");
        //从1970 - 01 - 01 00:00:00 截止到当前时间的毫秒值
        long l = System.currentTimeMillis();
        System.out.println(l);
        long time = new Date().getTime();
        //JDK1.8 Instant 时间戳类从1970 -01 - 01 00:00:00 截止到当前时间的毫秒值
        Instant now1 = Instant.now();
        //toEpochMilli():从1970 -01 - 01 00:00:00 截止到当前时间间隔的毫秒值
        long l1 = now1.toEpochMilli();
        System.out.println(l1);
        //获取从1970 -01 - 01 00:00:00 截止到当前时间间隔的秒值
        long epochSecond = now1.getEpochSecond();
        System.out.println(epochSecond);
        System.out.println("==========================");
        //给计算机元年增加相应的时间量
        Date date = new Date(1000 * 60 * 60*24);
        System.out.println(date);
        //现在 给计算机元年增加相应的时间量
        //5. ofEpochSecond() 方法 给计算机元年增加秒数
        //ofEpochMilli() 给计算机元年增加毫秒数
        Instant instant = Instant.ofEpochMilli(1000 * 60 * 60 * 24);
        System.out.println(instant);
        //ofEpochSecond() 方法 给计算机元年增加秒数
        Instant instant1 = Instant.ofEpochSecond(60 * 60 * 24);
        System.out.println(instant1);
    }
}
那么,现在本人来展示下运行结果:
Duration类 —— 用于计算两个“时间”间隔的类:
常用API:
- 静态方法 between():
计算两个时间的间隔,默认是秒- toDays():
将时间转换为以天为单位的- toHours():
将时间转换为以时为单位的- toMinutes():
将时间转换为以分钟为单位的- toMillis():
将时间转换为以毫秒为单位的- toNanos():
将时间转换为以纳秒为单位的
那么,现在本人来通过一段代码展示下这些API的使用:
package edu.youzg.about_new_features.core.about_jdk8.core;
import java.time.Duration;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Date;
public class Test {
    public static void main(String[] args) {
        //计算时间的间隔
        Instant start = Instant.now();
        for (int i = 0; i < 15; i++) {
            System.out.println(i);
        }
        Instant end = Instant.now();
        Duration duration = Duration.between(start, end);
        long l = duration.toNanos();
        //间隔的时间
        System.out.println("循环耗时:"+l+"纳秒");
    }
}
现在,本人来展示下运行结果:
Period类 —— 用于计算两个“日期”间隔的类:
- 静态方法 between():
计算两个日期之间的间隔- getYears():
获取年份- getMonths():
获取月份- getDays():
获取天数
那么,现在本人来通过一段代码展示下这些API的使用:
package edu.youzg.about_new_features.core.about_jdk8.core;
import java.time.*;
public class Test {
    public static void main(String[] args) {
        //计算两个日期的间隔
        LocalDate birthday = LocalDate.of(2012, 12, 12);
        LocalDate now = LocalDate.now();
        //我从出生到现在,有多少岁,零几个月,几天
        //计算两个日期的间隔
        Period between = Period.between(birthday, now);
        int years = between.getYears();
        int months = between.getMonths();
        int days = between.getDays();
        System.out.println("玛雅人的地球都消灭了"+years+"年"+months+"月"+days+"天了...");
    }
}
那么,现在,本人来展示下运行结果:
DateTimeFormatter类 —— 解析和格式化日期或时间的类
本人现在来展示下这个类的常用API :
- 静态方法ofPattern("yyyy-MM-dd"):
通过给定格式获取对象- format():
把一个日期对象的默认格式 格式化成指定的格式的字符串
那么,现在,本人来展示下这个类的使用:
package edu.youzg.about_new_features.core.about_jdk8.core;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
public class Test {
    public static void main(String[] args) {
        // 之前格式化日期的类  new SimpleDateFormat()
        //JDK1.8 DateTimeFormatter
        //指定格式 静态方法 ofPattern()
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // DateTimeFormatter 自带的格式方法
        LocalDateTime now = LocalDateTime.now();
        //把日期对象,格式化成字符串
        String format = formatter.format(now);
        //刚才的方式是使用的日期自带的格式化方法
        String format1 = now.format(formatter);
        System.out.println(format);
        System.out.println(format1);
    }
}
那么,现在本人来展示下运行结果:
ZonedDate、ZonedTime、ZonedDateTime —— 带时区的时间或日期
概述:
这个三个类方法及用法和 LocalDate、 LocalTime、 LocalDateTime 基本一样
只不过ZonedDate,ZonedTime、ZonedDateTime 这三个带有当前系统的默认时区的时间表示类
那么使用这三个类,就不得不介绍下 ZoneID类:
ZoneID —— 世界时区类:
常用API:
- getAvailableZoneIds():
.获取世界各个地方的时区的集合- systemDefault():
获取系统默认时区的ID- of(String zoneName):
根据各个地区的时区ID名创建对象
那么,现在,本人就来展示下这几个类的使用:
package edu.youzg.about_new_features.core.about_jdk8.core;
import java.time.*;
import java.util.Set;
public class Test {
    public static void main(String[] args) {
        //ZoneID 世界时区类
        //获取世界各地的时区编号。
        Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
        for (String availableZoneId : availableZoneIds) {
            System.out.println(availableZoneId);
        }
        System.out.println("=====================");
        //获取系统的默认时区编号
        ZoneId zoneId = ZoneId.systemDefault();
        System.out.println(zoneId);
        //获取其他国家的日期
        LocalDateTime now = LocalDateTime.now();
        //获取指定时区的日期时间
        ZoneId zoneId1 = ZoneId.of("Europe/Monaco");
        ZonedDateTime zonedDateTime = now.atZone(zoneId1);  //获得指定时区的当前时间
        System.out.println(zonedDateTime);
        System.out.println("=====================");
        //根据时区,获取该地区的日期
        LocalDateTime now1 = LocalDateTime.now(ZoneId.of("America/Phoenix"));  //获得指定时区的当前时间(不带时区信息)
        System.out.println(now1);
    }
}
由于世界各地的时区编号太多,所以,本人仅展示最后的几个输出结果:
来源:https://www.cnblogs.com/codderYouzg/p/12419127.html