2

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)
  1. 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.]

  2. Secondary question: How do I output c as YYYY-MM-DD HH-MM-SS?

2 Answers 2

5

Let a lib do that for you, like http://momentjs.com/

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");
Sign up to request clarification or add additional context in comments.

3 Comments

The library could help, but your example doesn't solve the problem I supplied. Can moment take the string '1:00:00' and add it to a timestamp? It doesn't look like it.
there it is, nearly too easy to be true ;)
This example should be in the docs (and among its first few lines) of moment.js ... it is not immediately obvious on that site that moment.js can "take in" some date format and convert it to another format.
2

For your second question, I'd recommend 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 comment, but yeah. rep.

2 Comments

I didn't downvote you, but you should fix your answer by supplying the actual answer, with code.
Well I would've posted this as a comment, but since there's this rule that I CAN'T.. Think it's strange you can post an answer but not a comment anyway, only trying to help here. Should stop doing that since I just get downvoted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.