Comparing time and time operations in Java

Hello. I want to create an application that is different in behavior if it is morning, noon, evening, evening. Now I want to set some variables with time for each. For example, noon = 12:00 Now I want to compare the current time with them and see if it is, for example, morning, and calculate how much until noon 12:00 is the current time. Now I have seen several examples with different dates, but I want to compare only by the clock.

+3
source share
4 answers

You can use the joda hoursBetween time or you can use the 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 3 pm here 
    

.

  • JodaBetween:

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

question question.

+2
    Calendar cal=GregorianCalendar.getInstance();

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

.

+2

TL;DR

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

java.time

, . java.util.Date/.Calendar java.time, Java 8 .

LocalTime .

"", "" .. . .

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

. . , JVM . / . ZonedDateTime Instant (ZoneId).

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

a LocalTime ZonedDateTime .

LocalTime nowLocalTime = now.toLocalTime();

.

Boolean isMorning = nowLocalTime.isBefore( noon );

Duration .

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

Duration::toString , ISO 8601. PT38M2S, . ..

Duration ZonedDateTime, , , (DST). 24- , LocalTime Duration.between.

+2

You can use GregorianCalendar for this. Create a new GregorianCalendar and set the month, day and year to some constant value. Set the hour at any time that interests you, i.e. 12:00 at noon. Now just getTimeInMillis () and save this value. You can later create another GregorianCalendar with a no-arg version to get the current time. Set the month, day, and year to the same constant value as your test value, and then just compare getTimeInMillis () again to see if it was earlier, equal to or after the reference time of day.

0
source

Source: https://habr.com/ru/post/1788325/


All Articles