英文:
How to get a particular time in a java.util.Date in Java 8
问题
例如 - 我想要 21:30 作为 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();
在 Java 8 中是否有更好的方法?
我只想要 java.util.Date,因为我想在构建触发器时将 Date 传递给 Quartz API 中的 endAt() 方法。
英文:
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.
答案1
得分: 3
新的java.time类转换为java.util.Date通常会经过Instant
类。例如,要将LocalTime 21:30转换为今天的日期和系统时区,您可以使用:
LocalTime nineThirty = LocalTime.of(21, 30);
Date d = Date.from(Instant.from(nineThirty.atDate(LocalDate.now())
.atZone(ZoneId.systemDefault())))
对于Quartz,您可能希望使用Quartz中的DateBuilder
类,而不是传统的Calendar
类。
Date d = DateBuilder.todayAt(21, 30, 0);
英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论