小工具知识网

当前位置: 首页 > 行业知识 > 详细分析Java中的LocalDateTime类

行业知识

详细分析Java中的LocalDateTime类

2026-12-05 06:34:43 来源:互联网转载

目录

  • 前言
  • 1. 基本知识
  • 2. 常用方法
  • 3. 当前时间戳
  • 4. 格式转换

    前言

    一开始使用Date类来表述时间属性

    一个问题是 时间戳的问题,另一个问题是读取Excel数据格式的时候没有那么灵活

    1. 基本知识

    LocalDateTime是Java 8引入的日期和时间API中的一个类,位于java.time包中。

    它提供了一种更灵活、更方便的方式来处理日期和时间,相比旧的Date类更为强大且易用。

    以下是关于LocalDateTime的详细分析:

    • 概念: LocalDateTime表示不带时区的日期和时间。

      包含了年、月、日、时、分、秒等信息,可以精确到纳秒级别。

      与Date类不同,LocalDateTime不受时区的影响,更适合处理应用程序中不涉及时区转换的日期和时间。

    • 作用: LocalDateTime用于表示和处理不带时区信息的日期和时间,适用于大多数应用场景,特别是与用户直接交互或与本地系统相关的情况。


      LocalDateTime类的关键特征:

      1. LocalDateTime是java.time包中的一个不可变类(immutable class)。
      2. 内部实现使用了LocalDate和LocalTime。
      3. 不包含时区信息,是一个本地日期和时间的组合。

      最主要的特性如下:

      1. 不可变性(Immutability): LocalDateTime是不可变的,这意味着一旦创建了对象,就无法更改其内容。任何对日期和时间的修改都会返回一个新的LocalDateTime对象。

      2. 线程安全性: 由于不可变性,LocalDateTime是线程安全的。多个线程可以同时访问对象而无需担心并发问题。

      3. 工厂方法: 除了使用of方法创建LocalDateTime对象外,还有一些静态工厂方法,如now、ofInstant、ofEpochSecond等,用于根据不同的情况创建实例。

      4. 日期时间调整: LocalDateTime提供了plus、minus等方法,用于执行日期和时间的调整操作。这些方法返回新的对象,而不是修改原始对象。

      5. 格式化和解析: LocalDateTime支持DateTimeFormatter用于格式化和解析日期时间。你可以创建自定义的格式化模式。

      2. 常用方法

      1. 获取当前日期时间:
      LocalDateTime currentDateTime = LocalDateTime.now();
      1. 创建指定日期时间:
      LocalDateTime specificDateTime = LocalDateTime.of(2022, Month.JANUARY, 1, 12, 30);
      1. 获取日期和时间部分:
      LocalDate datePart = specificDateTime.toLocalDate();LocalTime timePart = specificDateTime.toLocalTime();
      1. 日期时间加减操作:
      LocalDateTime newDateTime = specificDateTime.plusDays(1).minusHours(3);
      1. 比较:
      boolean isAfter = specificDateTime.isAfter(currentDateTime);
      1. 格式化和解析:
      DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");String formattedDateTime = specificDateTime.format(formatter);LocalDateTime parsedDateTime = LocalDateTime.parse("2022-01-01 12:30:00", formatter);

      类似的Demo如下:

      import java.time.LocalDateTime;import java.time.format.DateTimeFormatter;public class LocalDateTimeExample {    public static void main(String[] args) {        // 获取当前日期时间        LocalDateTime currentDateTime = LocalDateTime.now();        System.out.println("Current DateTime: " + currentDateTime);        // 创建指定日期时间        LocalDateTime specificDateTime = LocalDateTime.of(2022, 1, 1, 12, 30);        System.out.println("Specific DateTime: " + specificDateTime);        // 比较        boolean isAfter = specificDateTime.isAfter(currentDateTime);        System.out.println("Is specificDateTime after currentDateTime? " + isAfter);        // 格式化和解析        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");        String formattedDateTime = specificDateTime.format(formatter);        System.out.println("Formatted DateTime: " + formattedDateTime);        LocalDateTime parsedDateTime = LocalDateTime.parse("2022-01-01 12:30:00", formatter);        System.out.println("Parsed DateTime: " + parsedDateTime);    }}

      截图如下:


      对于上述的API为获取整体,如果获取细节也是可以的!

      1. 获取年份:(返回LocalDateTime对象的年份部分)
      int year = localDateTime.getYear();
      1. 获取月份:(返回LocalDateTime对象的月份部分)
      Month month = localDateTime.getMonth(); //getMonth()返回Month枚举类型int monthValue = localDateTime.getMonthValue(); //getMonthValue()返回月份的整数值
      1. 获取天(日):
      int dayOfMonth = localDateTime.getDayOfMonth(); //返回月份中的天数。int dayOfYear = localDateTime.getDayOfYear(); //返回年份中的天数。DayOfWeek dayOfWeek = localDateTime.getDayOfWeek();//返回星期几,返回的是DayOfWeek枚举类型。
      1. 获取小时、分钟、秒:(返回LocalDateTime对象的时、分、秒部分)
      int hour = localDateTime.getHour();int minute = localDateTime.getMinute();int second = localDateTime.getSecond();
      1. 其他时间信息:(返回纳秒部分)
      int nano = localDateTime.getNano();

      示例的Demo如下:

      import java.time.*;public class LocalDateTimeExample {    public static void main(String[] args) {        LocalDateTime localDateTime = LocalDateTime.now();        // 获取年份        int year = localDateTime.getYear();        System.out.println("Year: " + year);        // 获取月份        Month month = localDateTime.getMonth();        int monthValue = localDateTime.getMonthValue();        System.out.println("Month: " + month + " (" + monthValue + ")");        // 获取天(日)        int dayOfMonth = localDateTime.getDayOfMonth();        int dayOfYear = localDateTime.getDayOfYear();        DayOfWeek dayOfWeek = localDateTime.getDayOfWeek();        System.out.println("Day of Month: " + dayOfMonth);        System.out.println("Day of Year: " + dayOfYear);        System.out.println("Day of Week: " + dayOfWeek);        // 获取小时、分钟、秒        int hour = localDateTime.getHour();        int minute = localDateTime.getMinute();        int second = localDateTime.getSecond();        System.out.println("Hour: " + hour);        System.out.println("Minute: " + minute);        System.out.println("Second: " + second);        // 获取其他时间信息        int nano = localDateTime.getNano();        System.out.println("Nano: " + nano);    }}

      截图如下:

      3. 当前时间戳

      import java.text.SimpleDateFormat;import java.time.Clock;import java.time.Instant;import java.time.LocalDateTime;import java.time.ZoneOffset;import java.time.format.DateTimeFormatter;public class LocalDateTimeExample {    public static void main(String[] args) {        // 获取当前 LocalDateTime 对象        LocalDateTime currentDateTime = LocalDateTime.now();        // 将 LocalDateTime 转换为 Instant        Instant instant = currentDateTime.toInstant(ZoneOffset.of("+8"));        // 获取时间戳        long timestamp = instant.toEpochMilli();        System.out.println("Current Timestamp with LocalDateTime: " + timestamp);        //时间戳格式转换        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        System.out.println(df.format(timestamp));    }}

      或者另外一种表达方式:

      // 获取当前 LocalDateTime 对象LocalDateTime currentDateTime = LocalDateTime.now(Clock.systemUTC());// 将 LocalDateTime 转换为 InstantInstant instant = currentDateTime.toInstant(ZoneOffset.UTC);

      最终截图如下:

      4. 格式转换

      常用的格式转换为String与LocalDateTime之间!

      常用的方法有个格式转换的概括,但此处重点拿出来讲一讲:

      一、String 转换为 LocalDateTime:

      public class LocalDateTimeExample {    public static void main(String[] args) {        // String 转换为 LocalDateTime        String dateStr = "2024-01-21 21:00:00";        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");        LocalDateTime parsedDate = LocalDateTime.parse(dateStr, formatter);        System.out.println(parsedDate);        // String 转换为 LocalDate        String dateStr2 = "2024-01-21 21:00:00";        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");        LocalDate parsedDate2 = LocalDate.parse(dateStr2, formatter2);        System.out.println(parsedDate2);    }}

      截图如下:

      二、

      public class LocalDateTimeExample {    public static void main(String[] args) {        LocalDateTime date = LocalDateTime.now();        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");        String formatedDateStr = date.format(formatter);        System.out.println("-------" + formatedDateStr);    }}

      截图如下:

上一篇:语音唤醒小爱同学终极指南,轻松掌握一键启动秘籍!

下一篇:Kafka 架构