如何知道现在的时间是否在两个小时之间?

2022-09-02 00:09:28

我现在有时间:

new Date();

我有一些小时常量,例如,238(它是晚上11点或23:00,上午8点或08:00)。我怎么知道现在是两个小时常量之间的时间?

它需要运行一些程序代码,或者如果现在的时间在两个小时之间,则不运行,例如,如果它已经是晚上并且不是早上,则不要运行某些代码。

下图可以更好地解释:

enter image description here

静默模式不触发的某些情况:

00:00 20.06.13 - 23:00 20.06.13 // after 23.00 can loud!!

23:00 20.06.13 - 15:00 20.06.13 // after 15.00 can loud!!

01:00 20.06.13 - 08:00 20.06.13 // after 08.00 can loud!!

21:00 20.06.13 - 08:00 20.06.13 // after 08.00 can loud!!

答案 1

试试这个

    int from = 2300;
    int to = 800;
    Date date = new Date();
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    int t = c.get(Calendar.HOUR_OF_DAY) * 100 + c.get(Calendar.MINUTE);
    boolean isBetween = to > from && t >= from && t <= to || to < from && (t >= from || t <= to);

答案 2
Calendar cal = Calendar.getInstance(); //Create Calendar-Object
cal.setTime(new Date());               //Set the Calendar to now
int hour = cal.get(Calendar.HOUR_OF_DAY); //Get the hour from the calendar
if(hour <= 23 && hour >= 8)              // Check if hour is between 8 am and 11pm
{
     // do whatever you want
}

推荐