java 判断Date是上午还是下午
我要用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 格式化为字符串。
- 通过比较字符串判断是上午还是下午。这种方式的语言显示受系统默认语言环境影响。