如何在Java 8中从java.util.Date获取特定时间

huangapple go评论60阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年8月15日 23:12:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/63427555.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定