5

I have a string like :

var from = '2016-06-06T21:03:55' ;

Now how do I convert it into a timestamp such that I can give it as an input to momentjs. Basically, I want to find the difference in the timestamps as seen in this post : Get hours difference between two dates in Moment Js

Look at the last answer in the above post.

Please please help em out. I am stck on it since hours now.

Community
  • 1
  • 1
learntogrow-growtolearn
  • 1,190
  • 5
  • 13
  • 37
  • It's a valid date, so just `new Date(from)` would get you a date object, and the difference would be just `date1.getHours() - date2.getHours()` without an entire library to do it for you. – adeneo May 09 '16 at 23:26

2 Answers2

4

Option 1

You can initialize a Date object and call getTime() to get it in Unix form. It comes out in milliseconds so you'll need to divide by 1000 to get it in seconds.

(new Date("2016/06/06 21:03:55").getTime()/1000)

It may have decimal bits so wrapping it in Math.round would clean that.

Math.round(new Date("2016/06/06 21:03:55").getTime()/1000)

Demo: https://jsfiddle.net/nanilab/0jpxu30z/

Option 2

The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).

var input = "2016-06-06 21:03:55";
input = input.split(" - ").map(function (date){
    return Date.parse(date+"-0500")/1000;
}).join(" - ");

Demo: https://jsfiddle.net/nanilab/cweq2q0q/

enter image description here

agustin
  • 2,187
  • 2
  • 22
  • 40
  • Option 2 should be avoided: "It is not recommended to use Date.parse"... https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse – user2954463 Nov 12 '19 at 16:53
4

Pass this variable to the moment ctor.

var from = '2016-06-06T21:03:55' ;
var a = moment('2016-06-06T22:03:55');
var b = moment(from);

console.log(a.diff(b, 'minutes')); //60
console.log(a.diff(b, 'hours')); //1
console.log(a.diff(b, 'days')); //0 
console.log(a.diff(b, 'weeks')); //0

Or you can use the format method to see the value fo the moment variables, like :

b.format('DD/MM/YYYY hh:mm:ss'); // 06/06/2016 09:03:55
b.format(); // 2016-06-06T21:03:55+10:00
Ash
  • 2,575
  • 2
  • 19
  • 27