0

I have a back-end job that runs once a day and is scheduled at a particular time based on the entity/user etc.

Now, I want to validate if the current time is earlier than the job, if yes, then job can be rescheduled, else if job has already passed, then of course it cant be rescheduled for the day.

public static String getCurrentTime(String format) {
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    return sdf.format(cal.getTime());
}

String time = getCurrentTime("yyyy-MM-dd HH:mm:ss");
String backendJobTime = getBackendJobSchedule();
String[] onlyTime = time.split("\\s+");
String time = onlyTime[1];
Integer.parseInt(time);

Same for back-end job

if(time < backendJob){
    system.out.println("Job is yet to be exectued...):
}

Now,Ii want to get substring of time and then compare with other time of the back-end job and see if it's earlier. I can't write the complete logic.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
nick235
  • 7
  • 5
  • Does this answer your question? [Calculating the difference between two Java date instances](https://stackoverflow.com/questions/1555262/calculating-the-difference-between-two-java-date-instances) – Don Branson Jan 06 '22 at 17:29

1 Answers1

4

tl;dr

if(
    Instant
    .parse( "2022-07-14T22:15:00Z" )
    .isBefore( 
        Instant.now() 
    )
) { … }

Details

Never use the terrible legacy date-time classes Date, Calendar, SimpleDateFormat. These were supplanted years ago by the modern java.time classes defined in JSR 310.

You said:

getCurrentTime("yyyy-MM-dd HH:mm:ss")

You need more than a date and time-of-day to track a moment. For a specific point on the time line, you need the context of a time zone or offset from UTC.

In Java, track a moment as an Instant object. This class represents a moment as seen with an offset of zero hours-minutes-seconds from UTC.

Instant instant = Instant.now() ;

To serialize as text, use standard ISO 8601 formats.

String output = instant.toString() ;

2022-01-23T15:30:57.123456Z

The Z indicates an offset of zero. Pronounced “Zulu”.

And parse:

Instant instant = Instant.parse( "2022-01-23T15:30:57.123456Z" ) ;

Compare by calling isBefore, isAfter, and equals.

if( instant.isBefore( Instant.now() ) ) { … }

Notice that no time zone is involved in the code above. Perhaps you want to set the target time per your own time zone.

Instantiate a ZonedDateTime object. Extract an Instant to adjust to UTC (offset of zero).

ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
LocalDate ld = LocalDate.of( 2022 , Month.MARCH , 23 ) ;
LocalTime lt = LocalTime.of( 15 , 30 ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
Instant instant = zdt.toInstant() ;
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154