Home > Software engineering >  How to modify java Date to a specific time?
How to modify java Date to a specific time?

Time:10-26

I am running a script in Jenkins. One piece of the script need to run at 07:00:00 Eastern Time.

The job is already scheduled on specific days and time. The job starts at 6am, but need to wait until 7am to run the next step

Using java, I can get current time/date using:

Date currentDate = new Date()

I think I need to compare currentDate with today's date at 7am so I can know how many seconds there is until 7am and put my build to sleep for that time.

My question is, how can I generate today's date at 7am?

CodePudding user response:

Avoid using the terrible Date class. The legacy date-time classes were years ago supplanted by the modern java.time classes defined in JSR 310.

Capture the current moment as seen in your particular time zone.

ZoneId z = ZoneId.of( "America/New_York" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;

Define your target.

LocalTime targetTime = LocalTime.of( 7 , 0 ) ;

Adjust to that time.

ZonedDateTime zdtTarget = zdt.with( targetTime ) ;

If that moment has passed, move to next day.

if( ! zdt.isBefore( zdtTarget ) ) {
    zdtTarget = zdt.toLocalDate().plusDays( 1 ).atStartOfDay( z ).with( targetTime ) ;
}

Determine time to elapse.

Duration d = Duration.between( zdt.toInstant() , zdtTarget.toInstant() ) ;

Interrogate the duration object for whatever you need. For example, milliseconds:

long millis = d.toMillis() ;

If you must use a java.until.Date for code not yet updated to java.time, you can convert.

java.until.Date date = Date.from( zdtTarget.toInstant() ) ;

CodePudding user response:

Great question. It's easier to first create a Calendar object to set up the time, date and other custom inputs, then convert that to a Date object using the <CALENDAR_OBJECT>.getTime() member function. EX: to get a Date object of 7 am today(10/25/2021) do the following:

Calendar cal = Calendar.getInstance(); // Calendar constructor
cal.set(Calendar.YEAR, 2021);
cal.set(Calendar.MONTH, 10);
cal.set(Calendar.DAY_OF_MONTH, 25);
cal.set(Calendar.HOUR_OF_DAY,7);
cal.set(Calendar.MINUTE,00);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);

Date d = cal.getTime(); // convert to Date obj

For more info on the Calendar obj look at some documentation by Oracle (https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html)

  • Related