我有一个数据库,其时间戳保存在两个字段中,一个用于日期(2015-04-22),另一个用于时间(11:45:00)。
ResultSet rs = //db stuff
Date date = rs.getDate("date");
Time time = rs.getDate("time");
现在我想要一个日期对象,其中包含这两个对象的日期和时间。 我该怎么做?
答案 0 :(得分:2)
试试这个:
Date dateTime = new Date(date.getYear(), date.getMonth(), date.getDay(),
time.getHours(), time.getMinutes(), time.getSeconds());
或未弃用,优先解决方案:
Calendar calendarDate = Calendar.getInstance();
calendarDate.setTime(date);
Calendar calendarTime = Calendar.getInstance();
calendarTime.setTime(time);
Calendar calendarDateTime = Calendar.getInstance();
calendarDateTime.set(Calendar.YEAR, calendarDate.get(Calendar.YEAR));
calendarDateTime.set(Calendar.MONTH, calendarDate.get(Calendar.MONTH));
calendarDateTime.set(Calendar.DAY_OF_MONTH, calendarDate.get(Calendar.DAY_OF_MONTH));
calendarDateTime.set(Calendar.HOUR, calendarTime.get(Calendar.HOUR));
calendarDateTime.set(Calendar.MINUTE, calendarTime.get(Calendar.MINUTE));
calendarDateTime.set(Calendar.SECOND, calendarTime.get(Calendar.SECOND));
calendarDateTime.set(Calendar.MILLISECOND, calendarTime.get(Calendar.MILLISECOND));
Date dateTime = calendarDateTime.getTime();
答案 1 :(得分:0)
你应该使用格里高利历:
public GregorianCalendar(int year,
int month,
int dayOfMonth,
int hourOfDay,
int minute,
int second)
并从使用getter获得的Date
中删除值:
Date.getYear()
Date.getMonth()
Date.getDay()
Date.getHours()
Date.getMinutes()
Date.getSeconds()