最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Parsing MySQL TIME in javascript - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Nov 18, 2013 at 3:19 jmilloy asked Nov 8, 2013 at 21:26 jmilloyjmilloy 8,37514 gold badges58 silver badges87 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Let 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.

发布评论

评论列表(0)

  1. 暂无评论