I want to calculate the difference between two dateTime, one date is submitted by user and other is current time:
我想计算两个dateTime之间的差异,一个日期由用户提交,另一个是当前时间:
user submitted time - now = difference in unix
user submitted time format is:
用户提交的时间格式为:
2014-03-26 10:52:00
Thanks for your help.
谢谢你的帮助。
2 个解决方案
#1
4
You can simply do this with getTime()
which returns the number of milliseconds.
您可以使用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);
Sometimes there are chance for cross browser compatibility in parsing the date string so it is better to parse it like
有时在解析日期字符串时有可能存在跨浏览器兼容性,因此最好像解析它一样
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
#2
1
You can use MomentJS library
您可以使用MomentJS库
var user_submited_time = moment('2014-03-26 10:52:00');
var now = moment();
var value = user_submited_time - now;
#1
4
You can simply do this with getTime()
which returns the number of milliseconds.
您可以使用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);
Sometimes there are chance for cross browser compatibility in parsing the date string so it is better to parse it like
有时在解析日期字符串时有可能存在跨浏览器兼容性,因此最好像解析它一样
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
#2
1
You can use MomentJS library
您可以使用MomentJS库
var user_submited_time = moment('2014-03-26 10:52:00');
var now = moment();
var value = user_submited_time - now;