从日期加时间创建日期
Create Date from Date plus Time
我有一个数据库,时间戳保存在两个字段中,一个用于日期 (2015-04-22),一个用于时间 (11:45:00)。
ResultSet rs = //db stuff
Date date = rs.getDate("date");
Time time = rs.getDate("time");
现在我想要一个日期对象,其中包含这两个对象的日期和时间。
我该怎么做?
试试这个:
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();
你应该使用公历:
public GregorianCalendar(int year,
int month,
int dayOfMonth,
int hourOfDay,
int minute,
int second)
并从您使用吸气剂获得的 Date
中提取值:
Date.getYear()
Date.getMonth()
Date.getDay()
Date.getHours()
Date.getMinutes()
Date.getSeconds()
我有一个数据库,时间戳保存在两个字段中,一个用于日期 (2015-04-22),一个用于时间 (11:45:00)。
ResultSet rs = //db stuff
Date date = rs.getDate("date");
Time time = rs.getDate("time");
现在我想要一个日期对象,其中包含这两个对象的日期和时间。 我该怎么做?
试试这个:
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();
你应该使用公历:
public GregorianCalendar(int year,
int month,
int dayOfMonth,
int hourOfDay,
int minute,
int second)
并从您使用吸气剂获得的 Date
中提取值:
Date.getYear()
Date.getMonth()
Date.getDay()
Date.getHours()
Date.getMinutes()
Date.getSeconds()