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格式化为字符串。 - 通过比较字符串判断是上午还是下午。这种方式的语言显示受系统默认语言环境影响。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论