java.time包中的类如何使用

2024/1/4 1:32:44

本文主要是介绍java.time包中的类如何使用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

java.time包是在java8中引入的日期和时间处理API,提供了一组全新的类,用于更灵活、更强大的处理日期和时间。

常用用法

1、localDate

表示日期,不包含时间和时区信息

import java.time.LocalDate;

public class LocalDateExample {
    public static void main(String[] args) {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        System.out.println("Current Date: " + currentDate);

        // 创建指定日期
        LocalDate specificDate = LocalDate.of(2022, 1, 1);
        System.out.println("Specific Date: " + specificDate);

        // 执行日期操作
        LocalDate futureDate = currentDate.plusMonths(3);
        System.out.println("Future Date: " + futureDate);
    }
}

 2、loaclTime

表示时间,不包含日期和时区信息

import java.time.LocalTime;

public class LocalTimeExample {
    public static void main(String[] args) {
        // 获取当前时间
        LocalTime currentTime = LocalTime.now();
        System.out.println("Current Time: " + currentTime);

        // 创建指定时间
        LocalTime specificTime = LocalTime.of(12, 30, 45);
        System.out.println("Specific Time: " + specificTime);

        // 执行时间操作
        LocalTime futureTime = currentTime.plusHours(2);
        System.out.println("Future Time: " + futureTime);
    }
}

 3、LocalDateTime

表示日期和时间,不包含时区信息

import java.time.LocalDateTime;

public class LocalDateTimeExample {
    public static void main(String[] args) {
        // 获取当前日期和时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        System.out.println("Current Date and Time: " + currentDateTime);

        // 创建指定日期和时间
        LocalDateTime specificDateTime = LocalDateTime.of(2022, 1, 1, 12, 30);
        System.out.println("Specific Date and Time: " + specificDateTime);

        // 执行日期和时间操作
        LocalDateTime futureDateTime = currentDateTime.plusDays(7).minusHours(3);
        System.out.println("Future Date and Time: " + futureDateTime);
    }
}

 4、ZoneDateTime

表示带有时区的日期和时间

import java.time.ZonedDateTime;
import java.time.ZoneId;

public class ZonedDateTimeExample {
    public static void main(String[] args) {
        // 获取带有时区信息的当前日期和时间
        ZonedDateTime currentZonedDateTime = ZonedDateTime.now();
        System.out.println("Current Date and Time with Zone: " + currentZonedDateTime);

        // 创建指定时区的日期和时间
        ZonedDateTime specificZonedDateTime = ZonedDateTime.of(LocalDateTime.now(), ZoneId.of("America/New_York"));
        System.out.println("Specific Date and Time with Zone: " + specificZonedDateTime);
    }
}

 



这篇关于java.time包中的类如何使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程