Domanda

I have a now time:

new Date();

And I have some hour constants, for example, 23 and 8 (it's 11pm or 23:00, 8am or 08:00). How I can know is now time between it's two hour constants?

It need to run some code of program or not to run if now time is between in two hours, for example, do not run some code if its already evening and while it is not a morning.

Here the image to better explain:

enter image description here

Some situations when silent mode does not fire:

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!!
È stato utile?

Soluzione

try this

    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);

Altri suggerimenti

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
}

java.time

The modern way is with the java.time classes built into Java 8 and later. Much of the functionality is back-ported to Java 6 & 7 in the ThreeTen-Backport project and further adapted to Android in ThreeTenABP project.

Time zone is crucial here. For any given moment, the date and time-of-day both vary around the world by zone.

ZoneId z = ZoneId.of( "America/Montreal" );

Get your current moment.

ZonedDateTime zdt = ZonedDateTime.now( z );

Extract the time-of-day. The Local part of the name means there is no concept of time zone contained within the object.

LocalTime lt = zdt.toLocalTime();

Define the limits of the evening.

LocalTime start = LocalTime.of( 23 , 0 );  // 11 PM.
LocalTime stop = LocalTime.of( 8 , 0 );  // 8 AM.

Compare.

  • We need to figure out if we are straddling over a new day or within the same day. A LocalTime has no concept of date, only a single generic day of 24 hours. So we must test if the start is before or after the stop as we need different comparison algorithm for each case. And we should consider if the start equals the stop, as that may be a special case depending on your business rules.

  • In date-time work, we usually define spans of time as Half-Open, where the beginning is inclusive while the ending is exclusive.

Here's one way to do it.

Boolean silentRunning = null ;
if( start.equals( stop ) ) {
    silentRunning = Boolean.FALSE ;
} else if( stop.isAfter( start ) ) {  // Example 3 PM to 6 PM.
    silentRunning = ( ! lt.isBefore( start ) ) && lt.isBefore( stop ) ;
} else if ( stop.isBefore( start ) ) {  // Example 11 PM to 8 AM.
    silentRunning = ( lt.equals( start ) || lt.isAfter( start ) ) && lt.isBefore( stop ) ;
} else {
    // Error. Should not reach this point. Paranoid check.
}

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

  • Java SE 8 and SE 9 and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android

UPDATE: The above is a later version of this Answer. Below is the old.

Joda-Time

The Joda-Time library is vastly superior to the java.util.Date and .Calendar classes for date-time work.

Time zone is crucial for determine the time of day. Obviously "now" is later in the day in Paris than Montréal.

Definig a range of time is usually best done as half-open, [), where the beginning is inclusive but the ending is exclusive.

DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zone );
Integer hour = now.getHourOfDay();
Boolean isNight = ( ( hour >= 23  ) && ( hour < 8 ) );

I think that this is more cleaner solution and it`s works. I have tested it with different time parameters.

        /**
         * @param fromHour Start Time
         * @param toHour Stop Time
         * @param now Current Time
         * @return true if Current Time is between fromHour and toHour
         */
        boolean isTimeBetweenTwoHours(int fromHour, int toHour, Calendar now) {
            //Start Time
            Calendar from = Calendar.getInstance();
            from.set(Calendar.HOUR_OF_DAY, fromHour);
            from.set(Calendar.MINUTE, 0);
            //Stop Time
            Calendar to = Calendar.getInstance();
            to.set(Calendar.HOUR_OF_DAY, toHour);
            to.set(Calendar.MINUTE, 0);

            if(to.before(from)) {
                if (now.after(to)) to.add(Calendar.DATE, 1);
                else from.add(Calendar.DATE, -1);
            }
            return now.after(from) && now.before(to);
        }

You can see a tutorial here with Date.before and you can do with Date.after

Also you can get his milliseconds and compare it.

here is a function that checks is now(current time) is either between 1 to 4 OR 4 to 8 OR 8 to 12 OR 12 to 16 OR 16 to 20 OR 20 to 1 And returns next accuring time.

private Calendar GetTimeDiff() throws ParseException {
    Calendar now = Calendar.getInstance();

    Calendar one = Calendar.getInstance();
    one.set(Calendar.HOUR_OF_DAY, 1);
    one.set(Calendar.MINUTE, 0);
    one.set(Calendar.SECOND, 0);

    Calendar four = Calendar.getInstance();
    four.set(Calendar.HOUR_OF_DAY, 4);
    four.set(Calendar.MINUTE, 0);
    four.set(Calendar.SECOND, 0);

    Calendar eight = Calendar.getInstance();
    eight.set(Calendar.HOUR_OF_DAY, 8);
    eight.set(Calendar.MINUTE, 0);
    eight.set(Calendar.SECOND, 0);

    Calendar twelve = Calendar.getInstance();
    twelve.set(Calendar.HOUR_OF_DAY, 12);
    twelve.set(Calendar.MINUTE, 0);
    twelve.set(Calendar.SECOND, 0);

    Calendar sixteen = Calendar.getInstance();
    sixteen.set(Calendar.HOUR_OF_DAY, 16);
    sixteen.set(Calendar.MINUTE, 0);
    sixteen.set(Calendar.SECOND, 0);

    Calendar twenty = Calendar.getInstance();
    twenty.set(Calendar.HOUR_OF_DAY, 20);
    twenty.set(Calendar.MINUTE, 0);
    twenty.set(Calendar.SECOND, 0);

    if(now.getTime().after(one.getTime()) && now.getTime().before(four.getTime())) {
        return four;
    }

    if(now.getTime().after(four.getTime()) && now.getTime().before(eight.getTime())) {
        return eight;
    } 

    if(now.getTime().after(eight.getTime()) && now.getTime().before(twelve.getTime())) {
        return twelve;
    } 

    if(now.getTime().after(twelve.getTime()) && now.getTime().before(sixteen.getTime())) {
        return sixteen;
    } 

    if(now.getTime().after(sixteen.getTime()) && now.getTime().before(twenty.getTime())) {
        return twenty;
    } 

    if(now.getTime().after(twenty.getTime()) && now.getTime().before(one.getTime())) {
        return one;
    }

    return now;
}

PHP Solution

I wasn't able to find a solution for this in PHP, but @sytolk answer helped. heres the PHP version.

// $current = Date('H:i:s');
$current = "01:00:00";
$start = "23:00:00";
$end = "02:00:00";

$current = DateTime::createFromFormat('H:i:s', $current);
$start = DateTime::createFromFormat('H:i:s', $start);
$end = DateTime::createFromFormat('H:i:s', $end);

if ($end < $start) {
    if ($current > $end) {
        $end->modify('+1 day');
    } else {
        $start->modify('-1 day');
    }
}

$inTime = $current > $start && $current < $end;

You could also convert your input string to an integer and compare it against your constants. This way you don't even need to work with the Calendar and Date objects.

public class testDateRange {

    static final int START_HOUR = 8;
    static final int END_HOUR = 23;

    public static void main(String[] args) {
        String now_time = new SimpleDateFormat("HH:mm").format(new Date());
        System.err.println(isInRange(Integer.parseInt(now_time.replace(":","")),START_HOUR*100,END_HOUR*100));

    }

    private static boolean isInRange(int now_time, int start_time, int end_time) {

       if ((now_time>start_time)&&
               (now_time<end_time)       )
       {
        return true;
       }
        return false;
    }

}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top