// 获取当前小时的示例代码
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// 获取当前时间
LocalDateTime now = LocalDateTime.now();
// 获取当前小时,使用 getHour() 方法
int currentHour = now.getHour();
// 打印当前小时
System.out.println("当前小时: " + currentHour);
// 如果需要格式化输出,可以使用 DateTimeFormatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH");
String formattedHour = now.format(formatter);
// 打印格式化后的当前小时
System.out.println("格式化后的当前小时: " + formattedHour);
}
}
LocalDateTime.now()
获取当前的日期和时间。getHour()
方法从 LocalDateTime
对象中提取当前的小时数。该方法返回的是一个整数,范围是 0 到 23(24 小时制)。DateTimeFormatter
进行格式化。"HH"
表示 24 小时制的小时。希望这段代码能帮助你理解如何在 Java 中获取当前小时。
上一篇:java 时间比较大小
下一篇:java string 长度
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站