JDK8 日期时间的优化LocalDateTime&LocalDate和LocalTime

目录

一、简介

二、日期初识

三、时间初识

四、比较与计算

五、时区

六、格式化

七、相关类说明


 

一、简介

  在Java8之前,日期时间API一直被开发者诟病,包括:java.util.Date是可变类型,SimpleDateFormat非线程安全等问题。故此,Java8引入了一套全新的日期时间处理API,新的API基于ISO标准日历系统。

    

二、日期初识

  示例1: 获取当天日期

    Java 8中的 LocalDate 用于表示当天日期。和java.util.Date不同,它只有日期,不包含时间。

public static void main(String[] args) {
  LocalDate date = LocalDate.now();
  System.out.println("当前日期=" + date);
}

示例2: 构造指定日期

    调用工厂方法LocalDate.of()创建任意日期, 该方法需要传入年、月、日做参数,返回对应的LocalDate实例。这个方法的好处是没再犯老API的设计错误,比如年度起始于1900,月份是从0开 始等等

public static void main(String[] args) {
    LocalDate date = LocalDate.of(2000, 1, 1);
    System.out.println("千禧年=" + date);
}

  示例3: 获取年月日信息

public static void main(String[] args) {
    LocalDate date = LocalDate.now();
    System.out.printf("年=%d, 月=%d, 日=%d", date.getYear(), date.getMonthValue(), date.getDayOfMonth());
}

  示例4: 比较两个日期是否相等

public static void main(String[] args) {
    LocalDate now = LocalDate.now();
    LocalDate date = LocalDate.of(2018, 9, 24);
    System.out.println("日期是否相等=" + now.equals(date));
}
 

三、时间初识

  示例: 获取当前时间

    Java 8中的 LocalTime 用于表示当天时间。和java.util.Date不同,它只有时间,不包含日期。

public static void main(String[] args) {
    LocalTime time = LocalTime.now();
    System.out.println("当前时间=" + time);
}

四、比较与计算

  示例1: 日期时间计算

    Java8提供了新的plusXxx()方法用于计算日期时间增量值,替代了原来的add()方法。新的API将返回一个全新的日期时间示例,需要使用新的对象进行接收。

public static void main(String[] args) {
        
     // 时间增量
        LocalTime time = LocalTime.now();
        LocalTime newTime = time.plusHours(2);
        System.out.println("newTime=" + newTime);
        
     // 日期增量
        LocalDate date = LocalDate.now();
        LocalDate newDate = date.plus(1, ChronoUnit.WEEKS);
        System.out.println("newDate=" + newDate);
        
    }

示例2: 日期时间比较

    Java8提供了isAfter()、isBefore()用于判断当前日期时间和指定日期时间的比较

public static void main(String[] args) {
        
        LocalDate now = LocalDate.now();
        
        LocalDate date1 = LocalDate.of(2000, 1, 1);
        if (now.isAfter(date1)) {
            System.out.println("千禧年已经过去了");
        }
        
        LocalDate date2 = LocalDate.of(2020, 1, 1);
        if (now.isBefore(date2)) {
            System.out.println("2020年还未到来");
        }
        
    }

五、时区

  示例: 创建带有时区的日期时间

    Java 8不仅分离了日期和时间,也把时区分离出来了。现在有一系列单独的类如ZoneId来处理特定时区,ZoneDateTime类来表示某时区下的时间。

public static void main(String[] args) {
        
        // 上海时间
        ZoneId shanghaiZoneId = ZoneId.of("Asia/Shanghai");
        ZonedDateTime shanghaiZonedDateTime = ZonedDateTime.now(shanghaiZoneId);
        
        // 东京时间
        ZoneId tokyoZoneId = ZoneId.of("Asia/Tokyo");
        ZonedDateTime tokyoZonedDateTime = ZonedDateTime.now(tokyoZoneId);
        
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.out.println("上海时间: " + shanghaiZonedDateTime.format(formatter));
        System.out.println("东京时间: " + tokyoZonedDateTime.format(formatter));
        
    }

六、格式化

  示例1: 使用预定义格式解析与格式化日期

public static void main(String[] args) {
        
        // 解析日期
        String dateText = "20180924";
        LocalDate date = LocalDate.parse(dateText, DateTimeFormatter.BASIC_ISO_DATE);
        System.out.println("格式化之后的日期=" + date);
        
        // 格式化日期
        dateText = date.format(DateTimeFormatter.ISO_DATE);
        System.out.println("dateText=" + dateText);
        
    }

  示例2: 日期和字符串的相互转换

public static void main(String[] args) {
        
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        
        // 日期时间转字符串
        LocalDateTime now = LocalDateTime.now();
        String nowText = now.format(formatter);
        System.out.println("nowText=" + nowText);
        
        // 字符串转日期时间
        String datetimeText = "1999-12-31 23:59:59";
        LocalDateTime datetime = LocalDateTime.parse(datetimeText, formatter);
        System.out.println(datetime);
        
    }

七、相关类说明

Instant         时间戳
Duration        持续时间、时间差
LocalDate       只包含日期,比如:2018-09-24
LocalTime       只包含时间,比如:10:32:10
LocalDateTime   包含日期和时间,比如:2018-09-24 10:32:10
Peroid          时间段
ZoneOffset      时区偏移量,比如:+8:00
ZonedDateTime   带时区的日期时间
Clock           时钟,可用于获取当前时间戳
java.time.format.DateTimeFormatter      时间格式化类

备注:原文地址

以下是关于JDK 8日期相关类的介绍示例: 1. LocalDate类: - LocalDate类表示一个不可变的日期对象,它只包含日期部分(年、月、日)。 - 使用`now()`方法获取当前日期。 - 使用`of()`方法创建指定日期。 - 使用`getXXX()`方法获取日期的年、月、日等部分。 - 使用`plusXXX()``minusXXX()`方法进行日期的加减操作。 - 使用`isXXX()`方法判断日期的属性,如是否为闰年等。 示例代码: ```java import java.time.LocalDate; // 获取当前日期 LocalDate currentDate = LocalDate.now(); System.out.println("当前日期: " + currentDate); // 创建指定日期 LocalDate specificDate = LocalDate.of(2022, 1, 1); System.out.println("指定日期: " + specificDate); // 获取日期的年、月、日 int year = currentDate.getYear(); int month = currentDate.getMonthValue(); int day = currentDate.getDayOfMonth(); System.out.println("年: " + year + ", 月: " + month + ", 日: " + day); // 日期的加减操作 LocalDate futureDate = currentDate.plusDays(7); LocalDate pastDate = currentDate.minusMonths(1); System.out.println("未来日期: " + futureDate); System.out.println("过去日期: " + pastDate); // 判断是否为闰年 boolean isLeapYear = currentDate.isLeapYear(); System.out.println("是否为闰年: " + isLeapYear); ``` 2. LocalTime类: - LocalTime类表示一个不可变的时间对象,它只包含时间部分(时、分、秒、纳秒)。 - 使用`now()`方法获取当前时间。 - 使用`of()`方法创建指定时间。 - 使用`getXXX()`方法获取时间的时、分、秒等部分。 - 使用`plusXXX()``minusXXX()`方法进行时间的加减操作。 示例代码: ```java import java.time.LocalTime; // 获取当前时间 LocalTime currentTime = LocalTime.now(); System.out.println("当前时间: " + currentTime); // 创建指定时间 LocalTime specificTime = LocalTime.of(12, 30, 0); System.out.println("指定时间: " + specificTime); // 获取时间的时、分、秒 int hour = currentTime.getHour(); int minute = currentTime.getMinute(); int second = currentTime.getSecond(); System.out.println("时: " + hour + ", 分: " + minute + ", 秒: " + second); // 时间的加减操作 LocalTime futureTime = currentTime.plusHours(2); LocalTime pastTime = currentTime.minusMinutes(30); System.out.println("未来时间: " + futureTime); System.out.println("过去时间: " + pastTime); ``` 3. LocalDateTime类: - LocalDateTime类表示一个不可变的日期时间对象,它包含日期时间部分。 - 使用`now()`方法获取当前日期时间。 - 使用`of()`方法创建指定日期时间。 - 使用`getXXX()`方法获取日期时间的年、月、日、时、分、秒等部分。 - 使用`plusXXX()``minusXXX()`方法进行日期时间的加减操作。 示例代码: ```java import java.time.LocalDateTime; // 获取当前日期时间 LocalDateTime currentDateTime = LocalDateTime.now(); System.out.println("当前日期时间: " + currentDateTime); // 创建指定日期时间 LocalDateTime specificDateTime = LocalDateTime.of(2022, 1, 1, 12, 30, 0); System.out.println("指定日期时间: " + specificDateTime); // 获取日期时间的年、月、日、时、分、秒 int year = currentDateTime.getYear(); int month = currentDateTime.getMonthValue(); int day = currentDateTime.getDayOfMonth(); int hour = currentDateTime.getHour(); int minute = currentDateTime.getMinute(); int second = currentDateTime.getSecond(); System.out.println("年: " + year + ", 月: " + month + ", 日: " + day); System.out.println("时: " + hour + ", 分: " + minute + ", 秒: " + second); // 日期时间的加减操作 LocalDateTime futureDateTime = currentDateTime.plusDays(7); LocalDateTime pastDateTime = currentDateTime.minusMonths(1); System.out.println("未来日期时间: " + futureDateTime); System.out.println("过去日期时间: " + pastDateTime); ``` 4. Calendar类: - Calendar类是Java旧版的日期时间处理类,JDK 8之后推荐使用新的日期时间API。 - Calendar类可以用于获取设置日期时间的各个部分,如年、月、日、时、分、秒等。 - 使用`getInstance()`方法获取当前日期时间的Calendar实例。 - 使用`get()`方法获取日期时间的各个部分。 - 使用`set()`方法设置日期时间的各个部分。 示例代码: ```java import java.util.Calendar; // 获取当前日期时间的Calendar实例 Calendar currentCalendar = Calendar.getInstance(); System.out.println("当前日期时间: " + currentCalendar.getTime()); // 获取日期时间的年、月、日、时、分、秒 int year = currentCalendar.get(Calendar.YEAR); int month = currentCalendar.get(Calendar.MONTH) + 1; // 月份从0开始,需要加1 int day = currentCalendar.get(Calendar.DAY_OF_MONTH); int hour = currentCalendar.get(Calendar.HOUR_OF_DAY); int minute = currentCalendar.get(Calendar.MINUTE); int second = currentCalendar.get(Calendar.SECOND); System.out.println("年: " + year + ", 月: " + month + ", 日: " + day); System.out.println("时: " + hour + ", 分: " + minute + ", 秒: " + second); // 设置日期时间的年、月、日、时、分、秒 currentCalendar.set(Calendar.YEAR, 2022); currentCalendar.set(Calendar.MONTH, 0); // 月份从0开始,0表示1月 currentCalendar.set(Calendar.DAY_OF_MONTH, 1); currentCalendar.set(Calendar.HOUR_OF_DAY, 12); currentCalendar.set(Calendar.MINUTE, 30); currentCalendar.set(Calendar.SECOND, 0); System.out.println("设置后的日期时间: " + currentCalendar.getTime()); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值