一、不需要引入第三方j(luò)ar
import cn.hutool.core.date.DateUtil;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
/**
* 檢查當(dāng)前時(shí)間是否為夜間(22:00 到第二天6:00)
* @param dateTime 當(dāng)前時(shí)間戳 秒
* @return
*/
public static boolean checkNight(long dateTime){
try{
// 獲取當(dāng)前點(diǎn)位對(duì)應(yīng)的小時(shí)數(shù)
LocalDateTime localDateTime = getDateTimeOfTimestamp(dateTime * 1000);
int hour = localDateTime.getHour();
return (hour <= 5 || hour >= 22);
}catch (Exception e){
e.printStackTrace();
}
return false;
}
/**
* 時(shí)間戳 轉(zhuǎn) LocalDataTime
* @param timestamp 毫秒
* @return
*/
public static LocalDateTime getDateTimeOfTimestamp(long timestamp) {
Instant instant = Instant.ofEpochMilli(timestamp);
ZoneId zone = ZoneId.systemDefault();
return LocalDateTime.ofInstant(instant, zone);
}
二、使用 hutool 工具類
1、在 pom.xml 添加
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
<version>5.6.5</version>
</dependency>
2、使用 hutool 工具類
package com.example.jkytest.modules;
import cn.hutool.core.date.DateUtil;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public static void main(String[] args) throws ParseException {
String format = "HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(format);
//獲取當(dāng)前時(shí)間
// Date nowTime = new SimpleDateFormat(format).parse(Tools.getTimeString(calendar, format));
Date nowTime = sdf.parse("00:00:01");
//范圍開始時(shí)間
Date startTimeO = sdf.parse("22:00:00");
//范圍結(jié)束時(shí)間
Date endTimeO = sdf.parse("24:00:00");
//范圍開始時(shí)間
Date startTimeT = sdf.parse("00:00:00");
//范圍結(jié)束時(shí)間
Date endTimeT = sdf.parse("6:00:00");
System.out.println(DateUtil.isIn(nowTime,startTimeO,endTimeO) || DateUtil.isIn(nowTime,startTimeT,endTimeT));
}
對(duì)上圖使用方法
總結(jié)
如果此篇文章有幫助到您, 希望打大佬們能
關(guān)注
、點(diǎn)贊
、收藏
、評(píng)論
支持一波,非常感謝大家!
如果有不對(duì)的地方請(qǐng)指正!!!文章來源:http://www.zghlxwxcb.cn/news/detail-500943.html
參考1文章來源地址http://www.zghlxwxcb.cn/news/detail-500943.html
到了這里,關(guān)于java 判斷當(dāng)前時(shí)間在時(shí)間范圍內(nèi)方法的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!