Java时间类- 还不会用Java8中java.time类选择使用场景吗?

写在前面:世界纷纷绕绕,人终归是单一的。复杂只是迎合生存的写照,归宿终是孤独终老。技术本就无价,可惜世事弄人,潦倒众生。我辈岂能浑浑噩噩,只求思想自由矣矣。

前文回顾
为什么 Java 中的时间类如此繁多而复杂?
如何摆脱Java旧版时间类的困扰?Java 8新时间API带你轻松玩转时间

Java 8 引入的 java.time API 提供了强大且简洁的方式来处理日期和时间。以下是一些常见使用场景的代码示例,展示如何使用 java.time 包来处理日期、时间、时区等。

1. LocalDate:处理日期

LocalDate 只处理日期(年、月、日),不包含时间部分。

示例:获取当前日期,创建日期,比较日期
package com.example.springbootframework331.javadoc.time;

import java.time.LocalDate;

/**
 * @author zhizhou   2024/10/11 13:59
 */
public class LocalDateExample {
    public static void main(String[] args) {
        // 获取当前日期
        LocalDate today = LocalDate.now();
        System.out.println("今天的日期: " + today);
        
        // 创建指定日期
        LocalDate birthDate = LocalDate.of(1990, 5, 10);
        System.out.println("出生日期: " + birthDate);
        
        // 比较两个日期
        boolean isBefore = today.isBefore(birthDate);
        System.out.println("今天在出生日期之前吗? " + isBefore);
        
        // 日期加减
        LocalDate nextWeek = today.plusWeeks(1);
        System.out.println("一周后的日期: " + nextWeek);
    }
}

2. LocalTime:处理时间

LocalTime 只处理时间(时、分、秒、纳秒),不包含日期部分。

示例:获取当前时间,创建时间,计算时间差
package com.example.springbootframework331.javadoc.time;

/**
 * @author zhizhou   2024/10/11 13:59
 */
import java.time.LocalTime;
import java.time.Duration;

public class LocalTimeExample {
    public static void main(String[] args) {
        // 获取当前时间
        LocalTime now = LocalTime.now();
        System.out.println("当前时间: " + now);
        
        // 创建指定时间
        LocalTime meetingTime = LocalTime.of(14, 30);
        System.out.println("会议时间: " + meetingTime);
        
        // 计算两个时间之间的差异
        Duration duration = Duration.between(now, meetingTime);
        System.out.println("距离会议时间还有: " + duration.toHours() + " 小时");
        
        // 时间加减
        LocalTime later = now.plusHours(2);
        System.out.println("两小时后的时间: " + later);
    }
}

3. LocalDateTime:处理日期和时间

LocalDateTime 同时处理日期和时间(年、月、日、时、分、秒、纳秒),不包含时区信息。

示例:获取当前日期时间,创建日期时间,格式化日期时间
package com.example.springbootframework331.javadoc.time;

/**
 * @author zhizhou   2024/10/11 14:00
 */
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LocalDateTimeExample {
    public static void main(String[] args) {
        // 获取当前日期和时间
        LocalDateTime now = LocalDateTime.now();
        System.out.println("当前日期和时间: " + now);
        
        // 创建指定日期和时间
        LocalDateTime eventTime = LocalDateTime.of(2024, 10, 10, 14, 30);
        System.out.println("事件时间: " + eventTime);
        
        // 格式化日期时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);
        System.out.println("格式化后的日期时间: " + formattedDateTime);
    }
}

4. ZonedDateTime:处理带时区的日期和时间

ZonedDateTime 包含日期、时间和时区信息,适用于跨时区场景。

示例:获取当前时区的时间,转换为其他时区
package com.example.springbootframework331.javadoc.time;

/**
 * @author zhizhou   2024/10/11 14:00
 */
import java.time.ZonedDateTime;
import java.time.ZoneId;

public class ZonedDateTimeExample {
    public static void main(String[] args) {
        // 获取当前时区的日期时间
        ZonedDateTime nowInSystemZone = ZonedDateTime.now();
        System.out.println("当前时区的时间: " + nowInSystemZone);
        
        // 获取指定时区的日期时间
        ZonedDateTime nowInNewYork = ZonedDateTime.now(ZoneId.of("America/New_York"));
        System.out.println("纽约时区的时间: " + nowInNewYork);
        
        // 将当前时区的时间转换为指定时区
        ZonedDateTime nowInTokyo = nowInSystemZone.withZoneSameInstant(ZoneId.of("Asia/Tokyo"));
        System.out.println("东京时区的时间: " + nowInTokyo);
    }
}

5. Instant:处理时间戳

Instant 是 Java 的时间戳类,用于精确到秒或纳秒的瞬时时间点,适合用于记录日志或计算时间间隔。

示例:获取当前时间戳,计算两个时间点的差
package com.example.springbootframework331.javadoc.time;

import java.time.Instant;
import java.time.Duration;

/**
 * @author zhizhou   2024/10/11 13:02
 */
public class InstantExample {
    public static void main(String[] args) throws InterruptedException {
        // 获取当前时间戳
        Instant start = Instant.now();
        System.out.println("开始时间戳: " + start);
        
        // 模拟执行任务
        Thread.sleep(1000);
        
        // 获取任务结束的时间戳
        Instant end = Instant.now();
        System.out.println("结束时间戳: " + end);
        
        // 计算时间差
        Duration timeElapsed = Duration.between(start, end);
        System.out.println("耗时: " + timeElapsed.toMillis() + " 毫秒");
    }
}

6. DurationPeriod:处理时间段

Duration 表示时间段,精确到秒或纳秒;Period 表示日期段,精确到年、月、日。

示例:计算时间差
package com.example.springbootframework331.javadoc.time;

import java.time.Duration;
import java.time.LocalTime;
import java.time.LocalDate;
import java.time.Period;
import java.util.Date;

/**
 * @author zhizhou   2024/10/11 13:05
 */
public class DurationAndPeriodExample {
    public static void main(String[] args) {
        // 使用 Duration 计算时间差
        LocalTime startTime = LocalTime.of(8, 30);
        System.out.println("时间1: "+ startTime);
        System.out.println("---------------");
    
        LocalTime endTime = LocalTime.of(12, 31,10, 1);
        System.out.println("时间2: "+ endTime);
        System.out.println("---------------");
    
        Duration duration = Duration.between(startTime, endTime);
        System.out.println("时间差: " + duration);
        System.out.println("时间差: " + duration.toHours() + " 小时");
        System.out.println("---------------");
    
        // 使用 Period 计算日期差
        LocalDate startDate = LocalDate.of(2023, 1, 1);
        LocalDate endDate = LocalDate.of(2024, 1, 1);
        Period period = Period.between(startDate, endDate);
        System.out.println("日期差: " + period.getYears() + " 年");
    
    }
}

小结

java.time API 提供了丰富的类用于处理日期、时间、时区等场景。相比于旧的 DateCalendar,新的 API 更加简洁、直观和线程安全,特别适用于现代化的时间处理需求。在业务开发中,推荐优先使用 Java 8+ 的 java.time API 来实现日期和时间处理功能。

一个有想法的技术人:

技术和电子产品一样,选新款不选旧款,虽然旧款能用,但新款还是香。我们自视清高的技术人要时刻走在技术的前面,新的要学会接受,旧的真的可以先放一放或者直接摒弃,必要时再去查阅资料解决。。。要去开早会了…到这吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值