Java LocalDateTime 类
最后修改时间:2025 年 4 月 16 日
java.time.LocalDateTime
类表示 ISO-8601 日历系统中没有时区的日期时间。它结合了 LocalDate 和 LocalTime 来表示完整的日期和时间。LocalDateTime 是不可变的且线程安全的。
LocalDateTime
通常用于表示不需要时区的日期和时间。它以纳秒精度存储日期和时间。该类提供了用于日期时间算术和格式化的方法。
LocalDateTime 类概述
LocalDateTime
提供了创建、解析和操作日期时间值的方法。关键操作包括获取字段、执行计算以及转换为其他类型。该类处理从公元前 -999,999,999 年到公元 +999,999,999 年的日期。
public final class LocalDateTime implements Temporal, TemporalAdjuster, ChronoLocalDateTime<LocalDate>, Serializable { public static LocalDateTime now(); public static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute); public static LocalDateTime parse(CharSequence text); public int getYear(); public int getMonthValue(); public int getDayOfMonth(); public int getHour(); public int getMinute(); public LocalDateTime plusDays(long days); public LocalDateTime minusHours(long hours); public boolean isBefore(ChronoLocalDateTime<?> other); public boolean isAfter(ChronoLocalDateTime<?> other); }
上面的代码展示了 LocalDateTime
提供的关键方法。这些方法允许创建、比较和操作日期时间值。该类提供高达纳秒的精度,同时保持简单的 API。
创建 LocalDateTime 对象
LocalDateTime 对象可以通过多种方式创建。最常用的方法是 now
获取当前时间,以及用于特定日期时间的工厂方法。也支持从字符串解析。
package com.zetcode; import java.time.LocalDateTime; public class Main { public static void main(String[] args) { // Current date-time LocalDateTime now = LocalDateTime.now(); System.out.println("Current date-time: " + now); // Specific date-time LocalDateTime specific = LocalDateTime.of(2025, 5, 15, 14, 30); System.out.println("Specific date-time: " + specific); // From string LocalDateTime parsed = LocalDateTime.parse("2025-01-01T12:00:00"); System.out.println("Parsed from string: " + parsed); // Combining LocalDate and LocalTime LocalDateTime combined = LocalDateTime.of( java.time.LocalDate.now(), java.time.LocalTime.of(18, 30) ); System.out.println("Combined date-time: " + combined); } }
此示例演示了创建 LocalDateTime 对象的不同方法。输出以 ISO-8601 格式显示日期时间。 now
方法捕获当前的精确时刻,精度可达纳秒(如果可用)。
获取日期和时间组件
一个 LocalDateTime 可以分解成其日期和时间组件。这些值表示年、月、日、时、分等。这些方法对于提取日期时间的特定部分很有用。
package com.zetcode; import java.time.LocalDateTime; import java.time.Month; public class Main { public static void main(String[] args) { LocalDateTime dateTime = LocalDateTime.now(); // Date components int year = dateTime.getYear(); Month month = dateTime.getMonth(); int day = dateTime.getDayOfMonth(); System.out.println("Date: " + year + "-" + month.getValue() + "-" + day); // Time components int hour = dateTime.getHour(); int minute = dateTime.getMinute(); int second = dateTime.getSecond(); int nano = dateTime.getNano(); System.out.println("Time: " + hour + ":" + minute + ":" + second); System.out.println("Nanoseconds: " + nano); // Day of week System.out.println("Day of week: " + dateTime.getDayOfWeek()); } }
此示例展示了如何从 LocalDateTime 中提取组件。请注意,月份可以检索为 Month 枚举或数值。所有组件都可以通过简单的 getter 方法获得。
比较 LocalDateTime
可以比较 LocalDateTime 对象以确定时间顺序。该类提供 isBefore
、isAfter
和 compareTo
方法。这些比较对于基于日期时间的逻辑至关重要。
package com.zetcode; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; public class Main { public static void main(String[] args) { LocalDateTime now = LocalDateTime.now(); LocalDateTime later = now.plus(1, ChronoUnit.HOURS); LocalDateTime earlier = now.minus(30, ChronoUnit.MINUTES); System.out.println("Now is before later: " + now.isBefore(later)); System.out.println("Now is after earlier: " + now.isAfter(earlier)); System.out.println("Comparison result: " + now.compareTo(later)); // Equality check LocalDateTime copy = LocalDateTime.of( now.getYear(), now.getMonthValue(), now.getDayOfMonth(), now.getHour(), now.getMinute(), now.getSecond(), now.getNano() ); System.out.println("Now equals copy: " + now.equals(copy)); } }
此示例演示了比较 LocalDateTime 对象的各种方法。比较方法考虑所有日期和时间组件。请注意,相等性要求所有组件完全匹配。
添加和减去时间
LocalDateTime 通过 plus
和 minus
方法支持时间算术。这些操作对于计算未来或过去的日期时间很有用。该类自动处理字段之间的溢出。
package com.zetcode; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; public class Main { public static void main(String[] args) { LocalDateTime now = LocalDateTime.now(); // Add days LocalDateTime inOneWeek = now.plusDays(7); System.out.println("In one week: " + inOneWeek); // Subtract hours LocalDateTime twoHoursAgo = now.minusHours(2); System.out.println("Two hours ago: " + twoHoursAgo); // Add using ChronoUnit LocalDateTime nextMonth = now.plus(1, ChronoUnit.MONTHS); System.out.println("Next month: " + nextMonth); // Mixed operations LocalDateTime complex = now.plusDays(2) .minusHours(3) .plusMinutes(15); System.out.println("Complex operation result: " + complex); } }
此示例展示了使用 LocalDateTime 执行时间算术的各种方法。操作可以使用特定的单位方法或 ChronoUnit 常量。所有计算都精确到纳秒,并自动处理字段溢出。
在时间类型之间转换
LocalDateTime 可以与 Instant 或 ZonedDateTime 等其他时间类型进行相互转换。在处理时区或时间戳时,这些转换至关重要。
package com.zetcode; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.Instant; public class Main { public static void main(String[] args) { LocalDateTime now = LocalDateTime.now(); // Convert to ZonedDateTime ZonedDateTime zoned = now.atZone(ZoneId.of("Europe/Paris")); System.out.println("In Paris: " + zoned); // Convert to Instant (requires time zone) Instant instant = now.atZone(ZoneId.systemDefault()).toInstant(); System.out.println("As instant: " + instant); // Convert from Instant LocalDateTime fromInstant = LocalDateTime.ofInstant( Instant.now(), ZoneId.of("America/New_York")); System.out.println("From instant: " + fromInstant); // Convert to LocalDate or LocalTime System.out.println("Date part: " + now.toLocalDate()); System.out.println("Time part: " + now.toLocalTime()); } }
此示例演示了 LocalDateTime 和其他时间类型之间的转换。请注意,转换为 Instant 需要指定时区。所有转换都保留了所表示的确切日期和时间。
格式化和解析
LocalDateTime 支持通过 DateTimeFormatter 进行格式化和解析。这允许在字符串和日期时间对象之间进行灵活的转换。
package com.zetcode; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; import java.util.Locale; public class Main { public static void main(String[] args) { LocalDateTime now = LocalDateTime.now(); // Default format System.out.println("Default format: " + now); // Custom format DateTimeFormatter custom = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"); System.out.println("Custom format: " + now.format(custom)); // Localized format DateTimeFormatter localized = DateTimeFormatter .ofLocalizedDateTime(FormatStyle.MEDIUM) .withLocale(Locale.FRENCH); System.out.println("French format: " + now.format(localized)); // Parsing from custom format LocalDateTime parsed = LocalDateTime.parse( "2025/12/31 23:59:59", DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss") ); System.out.println("Parsed custom: " + parsed); } }
此示例展示了如何使用各种模式格式化和解析 LocalDateTime。 DateTimeFormatter 提供预定义和自定义格式化选项。本地化格式适应不同的文化惯例。
来源
在本文中,我们介绍了 Java LocalDateTime 类的基本方法和特性。理解这些概念对于在没有时区要求的 Java 应用程序中处理日期时间至关重要。
作者
列出所有Java教程。