Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I combine date from one timestamp and time from another timestamp?

Tags:

java

datetime

I using AngularJS to get date and time separately as user input through via HTML. But timestamp is a single column in my database.

Date and Time field are coming as two different timestamps in my Java server.

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

I want to combine date part from Date and time part from Time and insert as timestamp into my database

DateTime --> 2015-11-11 23:11:00.0
like image 298
codernac Avatar asked Aug 13 '15 14:08

codernac


2 Answers

Assuming you're able to create these as java.util.Date objects, you can rely on their milleseconds-from-epoch to get this information:

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

long dateTimeMills = dateMills + timeMills();

long dateTime = new Date(dateTimeMills);

Alternatively, you could set the fields individually.

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_OF_DAY);
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();
like image 166
corsiKa Avatar answered Nov 07 '22 13:11

corsiKa


No need to use the date and time as String, just use Calendar and get the fields separately:

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();
}
like image 22
Samuel Torga Avatar answered Nov 07 '22 13:11

Samuel Torga