Java LocalTime 类
最后修改时间:2025 年 4 月 16 日
java.time.LocalTime 类表示不包含日期或时区的时间。 它存储小时、分钟、秒和纳秒。 LocalTime 是不可变的且线程安全的,使其成为仅时间表示的理想选择。
LocalTime 通常用于存储营业时间、事件时间或任何仅时间部分重要的场景。 它提供高达纳秒的精度,并遵循 24 小时制格式。 该类无法表示时区或日期。
LocalTime 类概述
LocalTime 提供了创建、解析和操作时间的方法。 关键操作包括获取时间分量、比较时间和执行算术运算。 该类以小时、分钟、秒和纳秒为单位处理时间。
public final class LocalTime implements Temporal, TemporalAdjuster,
Comparable<LocalTime>, Serializable {
public static LocalTime now();
public static LocalTime of(int hour, int minute);
public static LocalTime of(int hour, int minute, int second);
public static LocalTime of(int hour, int minute, int second, int nanoOfSecond);
public static LocalTime parse(CharSequence text);
public int getHour();
public int getMinute();
public int getSecond();
public int getNano();
public boolean isAfter(LocalTime other);
public boolean isBefore(LocalTime other);
public LocalTime plusHours(long hours);
public LocalTime plusMinutes(long minutes);
public LocalTime minusHours(long hours);
public LocalTime minusMinutes(long minutes);
}
上面的代码显示了 LocalTime 提供的关键方法。 这些方法允许创建、比较和操作时间。 该类提供高达纳秒的精度,同时保持简单的仅时间表示。
创建 LocalTime 对象
可以通过多种方式创建 LocalTime 对象。 最常见的方法是 now 获取当前时间,以及工厂方法获取特定时间。 也支持从字符串解析。
package com.zetcode;
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
// Current time
LocalTime now = LocalTime.now();
System.out.println("Current time: " + now);
// Specific time
LocalTime lunchTime = LocalTime.of(12, 30);
System.out.println("Lunch time: " + lunchTime);
// With seconds
LocalTime preciseTime = LocalTime.of(14, 15, 30);
System.out.println("Precise time: " + preciseTime);
// With nanoseconds
LocalTime nanoTime = LocalTime.of(16, 45, 30, 123456789);
System.out.println("Nanosecond time: " + nanoTime);
// From string
LocalTime parsed = LocalTime.parse("23:59:59");
System.out.println("Parsed from string: " + parsed);
}
}
此示例演示了创建 LocalTime 对象的不同方法。 输出显示 ISO-8601 格式 (HH:mm:ss.nnn) 的时间。 now 方法使用可用精度捕获当前系统时间。
获取时间分量
可以将 LocalTime 分解为小时、分钟、秒和纳秒分量。 这些方法允许访问时间的各个部分以进行显示或计算。
package com.zetcode;
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
LocalTime time = LocalTime.of(15, 45, 30, 123456789);
// Get components
int hour = time.getHour();
int minute = time.getMinute();
int second = time.getSecond();
int nano = time.getNano();
System.out.println("Hour: " + hour);
System.out.println("Minute: " + minute);
System.out.println("Second: " + second);
System.out.println("Nanosecond: " + nano);
// Convert to seconds of day
int secondsOfDay = time.toSecondOfDay();
System.out.println("Seconds since midnight: " + secondsOfDay);
}
}
此示例展示了如何从 LocalTime 中提取分量。 toSecondOfDay 方法将时间转换为自午夜以来的秒数。 这对于基于时间的计算和比较非常有用。
比较时间
可以比较 LocalTime 对象以确定时间顺序。 该类提供了 isBefore、isAfter 和 compareTo 方法。 这些比较对于基于时间的逻辑至关重要。
package com.zetcode;
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
LocalTime morning = LocalTime.of(9, 0);
LocalTime afternoon = LocalTime.of(14, 30);
LocalTime evening = LocalTime.of(20, 0);
System.out.println("Morning before afternoon: " + morning.isBefore(afternoon));
System.out.println("Evening after afternoon: " + evening.isAfter(afternoon));
System.out.println("Comparison result: " + morning.compareTo(evening));
// Equality check
LocalTime sameAsMorning = LocalTime.of(9, 0);
System.out.println("Morning equals same time: " + morning.equals(sameAsMorning));
}
}
此示例演示了比较 LocalTime 对象的各种方法。 比较方法考虑所有时间分量。 请注意,相等性需要所有分量(包括纳秒)完全匹配。
添加和减去时间
LocalTime 通过 plus 和 minus 方法支持时间算术。 这些操作对于计算未来或过去的时间很有用。 该类自动处理溢出(24 小时环绕)。
package com.zetcode;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
LocalTime now = LocalTime.of(10, 30);
// Add hours
LocalTime later = now.plusHours(2);
System.out.println("Two hours later: " + later);
// Subtract minutes
LocalTime earlier = now.minusMinutes(45);
System.out.println("Forty-five minutes earlier: " + earlier);
// Add using ChronoUnit
LocalTime nextHour = now.plus(1, ChronoUnit.HOURS);
System.out.println("Next hour: " + nextHour);
// Wrap-around midnight
LocalTime lateNight = LocalTime.of(23, 0).plusHours(2);
System.out.println("After midnight: " + lateNight);
}
}
此示例显示了使用 LocalTime 执行时间算术的各种方法。 操作可以使用特定的单位方法或 ChronoUnit 常量。 所有计算都会自动处理午夜环绕。
格式化和解析
可以使用 DateTimeFormatter 格式化和解析 LocalTime。 这允许自定义显示格式和灵活的输入解析。 默认情况下使用 ISO-8601 格式。
package com.zetcode;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
LocalTime time = LocalTime.of(16, 45, 30);
// Default format
String defaultFormat = time.toString();
System.out.println("Default format: " + defaultFormat);
// Custom formatting
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm a");
String customFormat = time.format(formatter);
System.out.println("Custom format: " + customFormat);
// Parsing custom format
DateTimeFormatter parser = DateTimeFormatter.ofPattern("H.mm");
LocalTime parsedTime = LocalTime.parse("14.30", parser);
System.out.println("Parsed time: " + parsedTime);
}
}
此示例演示了格式化和解析 LocalTime 对象。 DateTimeFormatter 提供了灵活的基于模式的格式化。 解析支持标准和自定义格式。
时间范围操作
LocalTime 提供了检查时间是否在特定范围内或满足特定条件的方法。 这些操作对于基于时间的业务规则和验证非常有用。
package com.zetcode;
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
LocalTime businessStart = LocalTime.of(9, 0);
LocalTime businessEnd = LocalTime.of(17, 0);
LocalTime currentTime = LocalTime.now();
// Check if within business hours
boolean isBusinessHours = !currentTime.isBefore(businessStart)
&& currentTime.isBefore(businessEnd);
System.out.println("Is business hours: " + isBusinessHours);
// Check if midnight
boolean isMidnight = currentTime.equals(LocalTime.MIDNIGHT);
System.out.println("Is midnight: " + isMidnight);
// Check if AM or PM
boolean isAM = currentTime.getHour() < 12;
System.out.println("Is AM: " + isAM);
// Get min/max of two times
LocalTime earliest = LocalTime.min(businessStart, currentTime);
System.out.println("Earliest time: " + earliest);
}
}
此示例显示了使用 LocalTime 的各种范围和条件检查。 isBefore 和 isAfter 方法对于范围检查特别有用。 像 MIDNIGHT 这样的常量提供了常见的参考点。
来源
在本文中,我们介绍了 Java LocalTime 类的基本方法和功能。 理解这些概念对于 Java 应用程序中准确的仅时间表示至关重要。
作者
列出所有Java教程。