如何基于Java LocalDateTime实现时段问候输出?求代码示例
用LocalDateTime判断早晨/夜晚并输出问候语
没问题!我来帮你搞定这个需求——用LocalDateTime判断当前是早晨还是夜晚,然后输出"Good night"。其实isBefore()和isAfter()完全可以用来比较一天中的时间部分,不用只局限在日期上~
首先咱们得先明确“早晨”和“夜晚”的时间段,比如我先假设:
- 早晨:00:00 到 06:00
- 夜晚:22:00 到 23:59:59
你可以根据自己的需求随时调整这些时间点,下面给你两种实现方式:
方式一:直接用LocalDateTime处理
这种方式会保留日期信息,适合需要同时关注日期和时间的场景:
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class GreetingDemo { public static void main(String[] args) { // 你原有的代码 LocalDateTime now = LocalDateTime.now(); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd MMM yyyy , h:mm a"); System.out.println("当前时间: " + now.format(dtf)); // 定义早晨和夜晚的时间边界(基于当前日期) LocalDateTime morningStart = now.withHour(0).withMinute(0).withSecond(0).withNano(0); LocalDateTime morningEnd = now.withHour(6).withMinute(0).withSecond(0).withNano(0); LocalDateTime nightStart = now.withHour(22).withMinute(0).withSecond(0).withNano(0); LocalDateTime nightEnd = now.withHour(23).withMinute(59).withSecond(59).withNano(999999999); // 判断当前时间是否在早晨或夜晚区间内 boolean isMorning = now.isAfter(morningStart) && now.isBefore(morningEnd); boolean isNight = now.isAfter(nightStart) && now.isBefore(nightEnd); if (isMorning || isNight) { System.out.println("Good night"); } else { System.out.println("Hello!"); // 其他时间段的默认输出,可按需修改 } } }
方式二:用LocalTime单独处理时间(更简洁)
如果只需要关注一天中的时间,不需要日期,用LocalTime会更清爽:
import java.time.LocalDateTime; import java.time.LocalTime; import java.time.format.DateTimeFormatter; public class GreetingDemo { public static void main(String[] args) { LocalDateTime now = LocalDateTime.now(); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd MMM yyyy , h:mm a"); System.out.println("当前时间: " + now.format(dtf)); // 提取当前时间的时分秒部分 LocalTime currentTime = now.toLocalTime(); // 定义时间阈值 LocalTime morningEnd = LocalTime.of(6, 0); // 早晨结束于6点 LocalTime nightStart = LocalTime.of(22, 0); // 夜晚开始于22点 // 判断:要么在00:00-06:00,要么在22:00-23:59 boolean shouldSayGoodNight = currentTime.isBefore(morningEnd) || currentTime.isAfter(nightStart); if (shouldSayGoodNight) { System.out.println("Good night"); } else { System.out.println("Hello!"); } } }
小提示
- 如果需要包含区间端点(比如刚好6点整也输出"Good night"),可以用Java 9及以上支持的
isBeforeOrEqual()/isAfterOrEqual(),或者调整边界时间(比如把morningEnd设为6:00:00.000000001) - 时间段完全可以自定义,比如把早晨改成5点到8点,只需要修改
withHour()或者LocalTime.of()里的数值就行
内容的提问来源于stack exchange,提问作者Muhd Ikmal Asraf
相关产品推荐
相关产品推荐

