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
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();
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With