【发布时间】:2014-05-04 07:58:21
【问题描述】:
我想计算两个dateTime之间的差异,一个是用户提交的日期,另一个是当前时间:
user submitted time - now = difference in unix
用户提交时间格式为:
2014-03-26 10:52:00
感谢您的帮助。
【问题讨论】:
标签: javascript jquery datetime datepicker
我想计算两个dateTime之间的差异,一个是用户提交的日期,另一个是当前时间:
user submitted time - now = difference in unix
用户提交时间格式为:
2014-03-26 10:52:00
感谢您的帮助。
【问题讨论】:
标签: javascript jquery datetime datepicker
您可以简单地使用返回毫秒数的getTime() 执行此操作。
var ds = "2014-03-26 10:52:00";
var newDate = new Date(ds).getTime(); //convert string date to Date object
var currentDate = new Date().getTime();
var diff = currentDate-newDate;
console.log(diff);
有时在解析日期字符串时有机会实现跨浏览器兼容性,所以最好像这样解析它
var ds = "2014-03-26 10:52:00";
var dateArray = ds.split(" "); // split the date and time
var ds1 = dateArray[0].split("-"); // split each parts in date
var ds2 = dateArray[1].split(":"); // split each parts in time
var newDate = new Date(ds1[0], (+ds1[1] - 1), ds1[2], ds2[0], ds2[1], ds2[2]).getTime(); //parse it
var currentDate = new Date().getTime();
var diff = currentDate - newDate;
console.log(diff); //timestamp difference
【讨论】:
var newDate = new Date(ds1[0], (+ds1[1] - 1), ds1[2], ds2[0], ds2[1]).getTime();
你可以使用MomentJS库
var user_submited_time = moment('2014-03-26 10:52:00');
var now = moment();
var value = user_submited_time - now;
【讨论】: