结合java.util.Dates来创建日期时间

Ada*_*ski 21 java datetime

我目前有两个UI组件用于指定日期和时间.两个组件分别返回java.util.Date表示日历日期和时间的实例.我的问题是:

组合这些值以创建java.util.Date表示日期和时间的实例的最佳方法是什么? 我想避免依赖Joda或其他第三方库.

我目前的解决方案看起来像这样(但有更好的方法吗?):

Date date = ... // Calendar date
Date time = ... // Time

Calendar calendarA = Calendar.getInstance();
calendarA.setTime(date);

Calendar calendarB = Calendar.getInstance();
calendarB.setTime(time);

calendarA.set(Calendar.HOUR_OF_DAY, calendarB.get(Calendar.HOUR_OF_DAY));
calendarA.set(Calendar.MINUTE, calendarB.get(Calendar.MINUTE));
calendarA.set(Calendar.SECOND, calendarB.get(Calendar.SECOND));
calendarA.set(Calendar.MILLISECOND, calendarB.get(Calendar.MILLISECOND));

Date result = calendarA.getTime();
Run Code Online (Sandbox Code Playgroud)

dfa*_*dfa 15

public Date dateTime(Date date, Date time) {
    return new Date(
                     date.getYear(), date.getMonth(), date.getDay(), 
                     time.getHours(), time.getMinutes(), time.getSeconds()
                   );
}
Run Code Online (Sandbox Code Playgroud)

您可以将此已弃用的代码转换为日历以获取解决方案.

然后我的回答是:不,如果不使用joda,你就无法做得更好

NB

jodatime很快将与JSR 310标准化

  • 虽然我同意不应该使用它,但即使有人这样做,也许你应该为它们修复它.`date.getDay()`返回星期几.在这里你需要`day.getDate()` (3认同)