我要用Java生成表格统计信息,如下图所示:

所以就诞生了本文的内容。
在 Java 里,判断 Date 对象代表的时间是上午还是下午有多种方式,下面为你详细介绍不同的实现方法。
方式一:使用 java.util.Calendar
Calendar 类可以用来获取 Date 对象中的各个时间字段,通过 HOUR_OF_DAY 字段能判断是上午还是下午。
import java.util.Calendar;
import java.util.Date;
public class DateAmPmCheckWithCalendar {
public static void main(String[] args) {
// 创建一个 Date 对象
Date currentDate = new Date();
// 获取 Calendar 实例,并将 Date 对象设置进去
Calendar calendar = Calendar.getInstance();
calendar.setTime(currentDate);
// 获取 24 小时制的小时数
int hour = calendar.get(Calendar.HOUR_OF_DAY);
if (hour < 12) {
System.out.println("上午");
} else {
System.out.println("下午");
}
}
}
代码解释:
- 首先创建了一个
Date对象currentDate表示当前时间。 - 接着获取
Calendar实例,并使用setTime方法将currentDate设置进去。 - 通过
get(Calendar.HOUR_OF_DAY)获取 24 小时制的小时数。 - 根据小时数是否小于 12 判断是上午还是下午。
方式二:使用 java.time 包(Java 8 及以后)
Java 8 引入的 java.time 包提供了更简洁和强大的日期时间处理功能。可以将 Date 转换为 ZonedDateTime 再进行判断。
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
public class DateAmPmCheckWithJavaTime {
public static void main(String[] args) {
// 创建一个 Date 对象
Date currentDate = new Date();
// 将 Date 转换为 ZonedDateTime
ZonedDateTime zonedDateTime = currentDate.toInstant().atZone(ZoneId.systemDefault());
// 获取 24 小时制的小时数
int hour = zonedDateTime.getHour();
if (hour < 12) {
System.out.println("上午");
} else {
System.out.println("下午");
}
}
}
代码解释:
- 创建
Date对象currentDate。 - 使用
toInstant()方法将Date转换为Instant,再通过atZone(ZoneId.systemDefault())转换为ZonedDateTime。 - 调用
getHour()方法获取 24 小时制的小时数。 - 根据小时数判断是上午还是下午。
方式三:使用 SimpleDateFormat 格式化输出判断
可以使用 SimpleDateFormat 将 Date 格式化为包含上午/下午标识的字符串,然后进行判断。
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateAmPmCheckWithFormat {
public static void main(String[] args) {
// 创建一个 Date 对象
Date currentDate = new Date();
// 定义日期格式,使用 "a" 表示上午/下午标识
SimpleDateFormat sdf = new SimpleDateFormat("a");
// 格式化日期
String amPm = sdf.format(currentDate);
if ("上午".equals(amPm)) {
System.out.println("上午");
} else {
System.out.println("下午");
}
}
}
代码解释:
- 创建
Date对象currentDate。 - 创建
SimpleDateFormat对象,指定格式为"a",它会输出上午或下午。 - 使用
format方法将Date格式化为字符串。 - 通过比较字符串判断是上午还是下午。这种方式的语言显示受系统默认语言环境影响。















![[c语言日寄]越界访问:意外的死循环](https://i-blog.csdnimg.cn/direct/8e05ecb0bcdc43899c4a7e3f7e51d02e.png)



