简体   繁体   中英

How to get a particular time in a java.util.Date in Java 8

For eg - I want 21:30 as the java.util.Date

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,21);
cal.set(Calendar.MINUTE,30);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);

Date d = cal.getTime();

Is there a better way to do it in Java 8?

I want it in java.util.Date only as I want to pass a Date in endAt() method in Quartz api while building a Trigger.

Conversion of the new java.time classes to java.util.Date usually go through the Instant class. For example, to convert LocalTime 21:30 using today's date and the system time zone you can use:

LocalTime nineThirty = LocalTime.of(21, 30);

Date d = Date.from(Instant.from(nineThirty.atDate(LocalDate.now())
                                          .atZone(ZoneId.systemDefault())))

For Quartz specifically, you may want to use the DateBuilder class from Quartz instead of the legacy Calendar class.

Date d = DateBuilder.todayAt(21, 30, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM