3

Hello I wanna create app that has different behaviors if it is morning, noon, afternoon, evening. Now i wanna set some variables with the time for each For example noon = 12:00 Now i wanna compare current time with them and see if it is morning for example, and to calculate how much till noon 12:00 - current time. Now I've seen several examples with different dates, but i want to compare only by hour.

deemeetar
  • 31
  • 1
  • 3

4 Answers4

2

tl;dr

if ( 
    LocalTime.now( ZoneId.of( "Africa/Tunis” ) )
             .isBefore( LocalTime.of( 12 , 0 ) )
) {
    … // Do morning stuff. 
}

java.time

The other answers were correct but use outmoded classes. The java.util.Date/.Calendar classes have been supplanted by the java.time framework built into Java 8 and later.

The LocalTime class represents a time-of-day without a date and without a time zone.

Make some constants for your definition of "morning", "afternoon", and so on. In real work I would use an enum. But I'll use a simple variable here for the demo.

LocalTime noon = LocalTime.of( 12 , 0 );

Time zone is crucial to interpreting time-of-day. A time-of-day only has meaning in the context of a particular time zone. If not specified, your JVM’s current default time zone will automatically be applied silently. I strongly recommend you instead always explicitly specify the desired/expected time zone. You can think of a ZonedDateTime as being the combination of an Instant plus a time zone (ZoneId).

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now( zoneId );

We can extract a LocalTime from the ZonedDateTime according to its assigned time zone.

LocalTime nowLocalTime = now.toLocalTime();

Compare to the target time.

Boolean isMorning = nowLocalTime.isBefore( noon );

Use the Duration class to represent a span of time as a total number of seconds plus a fraction of a second in nanoseconds.

ZonedDateTime todayNoon = now.adjustInto( noon );
Duration untilNoon = Duration.between( now , todayNoon );

The default output of Duration::toString is a string in a format defined by ISO 8601. Example PT38M2S which thirty-eight minutes and two seconds. You can also ask for number of minutes, etc.

By getting a Duration from ZonedDateTime objects we will get an accurate result accounting for anomalies such as Daylight Saving Time (DST). If you would rather use a generic 24-hour day calculation, pass the LocalTime objects to Duration.between.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
2

You can use the joda time hoursBetween or you can use Java calendar class. I would recommend using JodaTime.

  • Using the Java Calendar class:

        Calendar future = Calendar.getInstance(); //future time
        future.set(Calendar.YEAR, 2011);
        future.set(Calendar.MONTH, 0);
        future.set(Calendar.DATE,27);
        future.set(Calendar.HOUR_OF_DAY,17);
        //get current time
        Calendar now = Calendar.getInstance();
        //time difference between now and future in hours
        long hoursDiff = (future.getTimeInMillis() - now.getTimeInMillis())/(60 * 60 * 1000);
        System.out.println("Difference in hours is ="+hoursDiff);//prints 2 since it's 3 pm here 
    

This does not factor in day light savings and compares against your LOCAL time zone.

  • Using Joda Time hoursBetween:

    DateTime futureDate = new DateTime(future.getTime());
    DateTime current = new DateTime(now.getTime());
    int difference = Hours.hoursBetween(current,futureDate).getHours();
    System.out.println("Difference in hours is ="+difference);
    

Also look at this question and this question.

Community
  • 1
  • 1
CoolBeans
  • 20,654
  • 10
  • 86
  • 101
2
    Calendar cal=GregorianCalendar.getInstance();

    int hour = cal.get(Calendar.HOUR);

Then compare the hour.

This will work for your local time zone

jny
  • 8,007
  • 3
  • 37
  • 56
0

You can use GregorianCalendar to do this. Create a new GregorianCalendar and set the month, day, and year to some constant value. Set the hour to whatever time you're interested in, ie 12:00 noon. Now just getTimeInMillis() and store that value. Later, you can create another GregorianCalendar with the no-arg version to get the current time. Set the month, day, and year to the same constant value as your benchmark value, and then just compare the getTimeInMillis() again to see if it is before, equal to, or after the reference time of day.

Jesse Barnum
  • 6,507
  • 6
  • 40
  • 69