我有一个日期
。我只想复制它的时间,不包括日期。然后我需要将时间插入另一个日期。
有没有简单的方法可以做到这一点?我无法更改日期数据类型。我可以做 getHour()、getMinutes() 等,但是这是冗长的。有没有我可以使用的更清晰的版本?或者可能是其他库,例如 apache commons 来设置/获取日期时间(到目前为止还没有发现任何内容)。
最佳答案
试试这个:
public static Date copyTimeOnly(Date toDate, Date fromDate) {
Calendar toCal = new GregorianCalendar();
toCal.setTime(toDate);
Calendar fromCal = new GregorianCalendar();
fromCal.setTime(fromDate);
// Copy time only
toCal.set(Calendar.HOUR_OF_DAY, fromCal.get(Calendar.HOUR_OF_DAY));
toCal.set(Calendar.MINUTE, fromCal.get(Calendar.MINUTE));
toCal.set(Calendar.SECOND, fromCal.get(Calendar.SECOND));
toCal.set(Calendar.MILLISECOND, fromCal.get(Calendar.MILLISECOND));
return toCal.getTime();
}
关于java - 在java中设置和获取日期的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27043427/