I get a MySQL TIMESTAMP
and MySQL TIME
from via an ajax request. What is a good way to add the time to the timestamp in javascript?
Given 2013-11-06 15:46:03
and 1:00:00
, the result should be 2013-11-06 16:46:03
. Below, I have a partial solution:
a = "2013-11-06 15:46:03";
b = "1:00:00";
//convert a to timestamp (in milliseconds)
a_ms = Date.parse(a);
//convert b to milliseconds
b_vals = b.split(':');
b_ms = 360000*bvals[0] + 60000*bvals[1] + 1000*bvals[2];
//add and convert to Date object
c = new Date(a_ms + b_ms); //Wed Nov 06 2013 15:52:03 GMT-0500 (EST)
Main question: Is there a better way to do this? For example, is there a better way to convert
b
to milliseconds? [edit: No libraries please. No matter how small, I wouldn't consider it "better" than parsing it myself in one line.]Secondary question: How do I output
c
asYYYY-MM-DD HH-MM-SS
?
I get a MySQL TIMESTAMP
and MySQL TIME
from via an ajax request. What is a good way to add the time to the timestamp in javascript?
Given 2013-11-06 15:46:03
and 1:00:00
, the result should be 2013-11-06 16:46:03
. Below, I have a partial solution:
a = "2013-11-06 15:46:03";
b = "1:00:00";
//convert a to timestamp (in milliseconds)
a_ms = Date.parse(a);
//convert b to milliseconds
b_vals = b.split(':');
b_ms = 360000*bvals[0] + 60000*bvals[1] + 1000*bvals[2];
//add and convert to Date object
c = new Date(a_ms + b_ms); //Wed Nov 06 2013 15:52:03 GMT-0500 (EST)
Main question: Is there a better way to do this? For example, is there a better way to convert
b
to milliseconds? [edit: No libraries please. No matter how small, I wouldn't consider it "better" than parsing it myself in one line.]Secondary question: How do I output
c
asYYYY-MM-DD HH-MM-SS
?
2 Answers
Reset to default 5Let a lib do that for you, like http://momentjs./
var a = moment("2013-11-06 15:46:03");
var b = moment(a).add('hours', 1);
var c = b.format("YYYY-MM-DD HH-mm-ss");
Edit to fit your requirement of also parsing the date difference:
var a = moment("2013-11-06 15:46:03");
var b = moment("1:00:00", "HH:mm:ss");
var c = moment(a).add(b).format("YYYY-MM-DD HH-mm-ss");
For your second question, I'd remend looking at these sites, they help me alot: Working with Dates and 10 ways to format time and date using JavaScript
P.S. I'd make it a ment, but yeah. rep.