3
我想计算两个日期时间之间的区别,一个日期是由用户提交的,另一个是当前时间:计算差异之间的两个时间戳并获得Unix时间戳差异
user submitted time - now = difference in unix
用户提交的时间格式为:
2014-03-26 10:52:00
感谢您的帮助。
我想计算两个日期时间之间的区别,一个日期是由用户提交的,另一个是当前时间:计算差异之间的两个时间戳并获得Unix时间戳差异
user submitted time - now = difference in unix
用户提交的时间格式为:
2014-03-26 10:52:00
感谢您的帮助。
你可以简单地用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
您可以使用MomentJS库
var user_submited_time = moment('2014-03-26 10:52:00');
var now = moment();
var value = user_submited_time - now;
谢谢,这是我要寻找的解决方案。我会尽力让你知道。 – user007
@ user007当然:),让我知道如果它没有奏效。 – Praveen
这不起作用,都给NaN。这是我的约会:'2014-03-26 12:50' – user007