组合java.util.Dates以创建日期时间 [英] Combining java.util.Dates to create a date-time
问题描述
java.util.Date
实例。我的问题是: 组合这些值以创建一个 java.util.Date
实例的最佳方法是什么代表日期和时间? 我想避免对Joda或其他第三方库的依赖。
我目前的解决方案看起来像这样(但是有更好的方法吗? ):
日期日期= ... //日历日期
日期时间= ... //时间
日历calendarA = Calendar.getInstance();
calendarA.setTime(date);
日历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));
日期结果= calendarA.getTime();
dateTime(Date date,Date time){
return new Date(
date.getYear(),date.getMonth(),date.getDay(),
time.getHours(),time .getMinutes(),time.getSeconds()
);
}
您可以将此不推荐使用的代码转换为获取解决方案的日历。
然后我的答案是:不,你不能做更好的没有使用joda
NB
jodatime很快将被标准化为 JSR 310
I have current have two UI components used to specify a date and a time. Both components return java.util.Date
instances representing the calendar date and time respectively. My question is:
What is the best way to combine these values to create a java.util.Date
instance representing the date and time? I would like to avoid dependencies on Joda or other 3rd party libraries.
My current solution looks like this (but is there a better way?):
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();
public Date dateTime(Date date, Date time) {
return new Date(
date.getYear(), date.getMonth(), date.getDay(),
time.getHours(), time.getMinutes(), time.getSeconds()
);
}
you can corvert this deprecated code to Calendar obtaining your solution.
Then my answer is: no, you cannot do better without using joda
NB
jodatime soon will be standardized with JSR 310
这篇关于组合java.util.Dates以创建日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!