3

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.

Praveen
  • 55,303
  • 33
  • 133
  • 164
user007
  • 3,203
  • 13
  • 46
  • 77

2 Answers2

4

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
Community
  • 1
  • 1
Praveen
  • 55,303
  • 33
  • 133
  • 164
  • 1
    Thanks, this is the solution I am looking for. I will try and let you know. – user007 Mar 26 '14 at 06:31
  • This is not working, both give NaN. This is my date: `2014-03-26 12:50` – user007 Mar 26 '14 at 07:15
  • 1
    @user007 missing to add seconds. Then change this line `var newDate = new Date(ds1[0], (+ds1[1] - 1), ds1[2], ds2[0], ds2[1]).getTime();` – Praveen Mar 26 '14 at 07:21
  • I already tried with, `2014-03-26 13:37:54` and this out NaN too – user007 Mar 26 '14 at 07:47
  • 1
    @user007 hmm okay lets check it out http://jsfiddle.net/praveen_jegan/LVmyj/1/ try with different values and let me know which one fails – Praveen Mar 26 '14 at 08:00
  • 1
    oh its working now, it was due to negative result. cuz user input time is for future. Thanks and your solution is perfect. – user007 Mar 26 '14 at 08:02
  • do i need to divide diff/1000 ? I think current time is in milliseconds – user007 Mar 26 '14 at 08:17
  • 1
    @user007 it depends, some use unix timestamp with 13 digit; other 10 digit which called as [Unix epoach timestamp](http://www.epochconverter.com/) – Praveen Mar 26 '14 at 08:19
  • I need epoch, for sending it to server. So I think you said I need o divide. thanks – user007 Mar 26 '14 at 08:21
1

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;