0

i have to subtract two days and need to get the total hours.

let date1 =  moment.tz(new Date(), "YYYY-MM-DDTHH:mm:ss", "America/Chicago").local().format('MM/DD/YYYY h:mm A');

let date2 =  moment.tz(titleDate, "YYYY-MM-DDTHH:mm:ss", "America/Chicago").local().format('MM/DD/YYYY h:mm A');


let getHours = date1.diff(date2, 'hours') 

i need to get the total hours like this way. any different way to resolve this issue ?

vishnusaran
  • 139
  • 1
  • 9
  • getting date1.diff(date2) is not a function error. – vishnusaran Sep 14 '18 at 07:26
  • 2
    Possible duplicate of [Get hours difference between two dates in Moment Js](https://stackoverflow.com/questions/25150570/get-hours-difference-between-two-dates-in-moment-js) – NineBerry Sep 14 '18 at 07:28
  • `diff ()` is function of `momentjs` not of `moment-timezone` library so make sure you have added `momentjs` library as well. – Vikasdeep Singh Sep 14 '18 at 08:14

4 Answers4

4

Also you can use,

let date1 =  moment.tz(new Date(), "YYYY-MM-DDTHH:mm:ss", "America/Chicago").local();
let date2 =  moment.tz(titleDate, "YYYY-MM-DDTHH:mm:ss", "America/Chicago").local();
var x = moment.duration(date1.diff(date2)).asHours();

from docs

benjamin c
  • 2,278
  • 15
  • 25
2

The format function returns a string. So, in your code, date1 and date2 are strings, not momentjs datetime values. Remove the call to format().

NineBerry
  • 26,306
  • 3
  • 62
  • 93
0

After formatted, the date1 does not have diff method which is a string. You can remove the format.

let date1 =  moment.tz(new Date(), "YYYY-MM-DDTHH:mm:ss", "America/Chicago").local();
let date2 =  moment.tz(titleDate, "YYYY-MM-DDTHH:mm:ss", "America/Chicago").local();
let getHours = date1.diff(date2, 'hours');

Or if date1 and date2 are in same timezone:

let date1 =  moment();
let date2 =  moment(titleDate);
let getHours = date1.diff(date2, 'hours');

Or

date1.diff(date2) / 1000 / 60 / 60;

date1.diff(date2) return milliseconds.

Bendy Zhang
  • 451
  • 2
  • 10
0

Try this:

var titleDate = new Date(2018, 11, 24, 10, 33, 30);
var originalDate1 = moment.tz(new Date(), "YYYY-MM-DDTHH:mm:ss", "America/Chicago").local();
var date1 =  originalDate1.format('MM/DD/YYYY h:mm A');
var originalDate2 = moment.tz(titleDate, "YYYY-MM-DDTHH:mm:ss", "America/Chicago").local();
var date2 =  originalDate2.format('MM/DD/YYYY h:mm A');
console.log(date1+"\n"+date2);
var duration = moment.duration(originalDate2.diff(originalDate1));//myMoment.diff(now, 'days', true);
var hoursDuration = duration.asHours();
console.log(hoursDuration);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.21/moment-timezone-with-data-2012-2022.js"></script>
protoproto
  • 2,081
  • 1
  • 13
  • 13