user007
user007

Reputation: 3243

calculate difference between two timestamp and get difference in unix timestamp

I want to calculate the difference between two dateTime, one date is submitted by user and other is current time:

user submitted time - now = difference in unix

user submitted time format is:

2014-03-26 10:52:00

Thanks for your help.

Upvotes: 3

Views: 8264

Answers (2)

Praveen
Praveen

Reputation: 56501

You can simply do this with getTime() which returns the number of milliseconds.

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

Upvotes: 4

Denis Tambovchanin
Denis Tambovchanin

Reputation: 556

You can use MomentJS library

 var user_submited_time = moment('2014-03-26 10:52:00');
 var now = moment();
 var value = user_submited_time - now;

Upvotes: 1

Related Questions