1

I seem to have more trouble than necessary.

I have a date in the past in string, say: 2017-01-09T10:23:13.000Z

I want to get the number of hours till now.

What operations should I perform?

so_user
  • 333
  • 3
  • 15
  • 6
    duplicate http://stackoverflow.com/questions/25150570/get-hours-difference-between-two-dates-in-moment-js – lordkain Jan 09 '17 at 14:35
  • 4
    Possible duplicate of [Get hours difference between two dates in Moment Js](http://stackoverflow.com/questions/25150570/get-hours-difference-between-two-dates-in-moment-js) – Stu Jan 09 '17 at 14:36

3 Answers3

0

use moment.duration and duration.asHours for this.

You can get the current datetime now using moment() and get the duration of now from the datetime you have as string.

var now = moment();
var duration = moment.duration(now.diff("2017-01-09T10:23:13.000Z"));
var hours = duration.asHours();
console.log(hours)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
Deep
  • 9,594
  • 2
  • 21
  • 33
0

You can use diff specifying 'hour' as second parameter.

Here a working example:

var time = '2017-01-09T10:23:13.000Z';
console.log(moment().diff(moment(time), 'h'));
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
VincenzoC
  • 30,117
  • 12
  • 90
  • 112
0

You should use moment.duration and duration.asHours methods.

var startTime=new moment(`2017-01-09T10:23:13.000Z`);
var end=moment();
var duration = moment.duration(end.diff(startTime));
var hours = duration.asHours();
console.log(parseInt(hours));

  var startTime=new moment(`2017-01-09T10:23:13.000Z`);
var end=moment();
var duration = moment.duration(end.diff(startTime));
var hours = duration.asHours();
console.log(parseInt(hours));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script>
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128