使用java代码如何检测一个时间属于的时间时段呢?
下文笔者讲述使用java代码检测时间属于具体的时间段(上午|中午|下午|晚上|凌晨),具体的实现方式如下所示
实现思路: 1.获取时间的hour信息 2.通过if语句判断时间所属的具体时间段例:检测一个Date所属的时间段
import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class TestClass { public static void main(String[] args) { Date date = new Date(); String pattern = "HH"; Locale locale = Locale.getDefault(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern, locale); String time = simpleDateFormat.format(date); int hour = Integer.parseInt(time); if (hour >= 0 && hour <= 6) { System.out.println("凌晨"); } if (hour > 6 && hour <= 12) { System.out.println("上午"); } if (hour > 12 && hour <= 13) { System.out.println("中午"); } if (hour > 13 && hour <= 18) { System.out.println("下午"); } if (hour > 18 && hour <= 24) { System.out.println("晚上"); } } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。