如何将来自一个时间戳的日期与来自另一个时间戳的时间相结合?

时间:2015-08-13 14:34:42

标签: java datetime

我使用AngularJS分别通过HTML输入日期和时间作为用户输入。但是时间戳是我数据库中的单个列。

日期和时间字段在我的Java服务器中作为两个不同的时间戳出现。

Date --> 2015-11-11 00:00:00.0
Time --> 1970-01-01 23:11:00.0

我希望将日期部分与日期和时间部分结合起来,并将其作为时间戳插入我的数据库

DateTime --> 2015-11-11 23:11:00.0

3 个答案:

答案 0 :(得分:2)

假设您能够将这些对象创建为java.util.Date,您可以依靠他们的milleseconds-from-epoch来获取此信息:

long dateMills = date.getTime();
long timeMills = time.getTime();

long dateTimeMills = dateMills + timeMills();

long dateTime = new Date(dateTimeMills);

或者,您可以单独设置字段。

GregorianCalendar dateCal = new GregorianCalendar();
GregorianCalendar timeCal = new GregorianCalendar();

dateCal.setTime(date.getTime());
timeCal.setTime(time.getTime());

int year = dateCal.get(Calendar.YEAR);
int month = dateCal.get(Calendar.MONTH);
int day = dateCal.get(Calendar.DAY_OF_MONTH);

int hour = timeCal.get(Calendar.HOUR);
int minute = timeCal.get(Calendar.MINUTE);
int second = timeCal.get(Calendar.SECOND);

GregorianCalendar dateTimeCal = new GregorianCaledar(year, month, day, hour, minute, second);
Date dateTime = dateTimeCal.getTime();

答案 1 :(得分:1)

无需将日期和时间用作String,只需使用Calendar并单独获取字段:

public static Date combineDateTime(Date date, Date time) {
    Calendar dateCalendar = Calendar.getInstance();
    dateCalendar.setTime(date);

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

    dateCalendar.set(Calendar.HOUR, timeCalendar.get(Calendar.HOUR));
    dateCalendar.set(Calendar.MINUTE, timeCalendar.get(Calendar.MINUTE));
    dateCalendar.set(Calendar.SECOND, timeCalendar.get(Calendar.SECOND));

    return dateCalendar.getTime();
}

答案 2 :(得分:0)

您可以简单地使用String.split并创建所需的String日期并根据需要使用它。

 SimpleDateFormat formatter = new SimpleDateFormat("hh:mm a");
 SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 String dateInString = "12:30 AM";
 String dateInString2 = "2017-10-16 10:00:00";
 try {
  Date date1 = formatter.parse(dateInString);
  Date date2 = formatter2.parse(dateInString2);
  String[] d1 = formatter2.format(date1).split(" ");
  String[] d2 = formatter2.format(date2).split(" ");
  String neededDate = d2[0] + " " + d1[1];
  System.out.println(date1);
  System.out.println(formatter2.format(date1));
  System.out.println(formatter2.format(date2));
  System.out.println(neededDate);
 } catch (ParseException e) {
  e.printStackTrace();
 }

输出

Thu Jan 01 00:30:00 IST 1970
1970-01-01 00:30:00
2017-10-16 10:00:00
2017-10-16 00:30:00