Reputation: 1056
I have a starting hour given in string.
let opens = '08:00';
I want to measure the difference in minutes for various dates.
let date1 = moment('1945.10.20 17:30');
let date2 = moment('1970.01.08 12:00');
// should result 570 (9.5h) and 240 (4h)
I was naive enough to try
moment(opens, 'HH:mm').diff(date1, 'm');
but I realized that it would make a date for the current day's hour.
Upvotes: 0
Views: 66
Reputation: 106640
Get a moment object on the same day, but with the hours you want. From there do the comparison. If you know the format of opens will always be HH:mm
then you can do this:
let opens = '08:00';
let opensTime = moment(opens, 'HH:mm');
let date1 = moment('1945.10.20 17:30', 'YYYY.MM.DD HH:mm');
let openDate1 = date1.clone().set({
hour: opensTime.hour(),
minute: opensTime.minute()
});
Then compare:
date1.diff(openDate1, 'm') === 570;
Alternatively, you could just do a split on opens
—opens.split(":")
—to get the hour and minute.
Upvotes: 2
Reputation: 5811
Can you modify the opens
variable?
let date1 = moment(new Date('1945.10.20 17:30'));
let date2 = moment(new Date('1970.01.08 12:00'));
function timeDifference(end, opensHour, opensMinute) {
var start = end.clone().set({
"hour": opensHour,
"minute": opensMinute
});
return {
"start": start,
"end": end,
"difference": end.diff(start, "minutes")
};
}
console.log(timeDifference(date1, 8, 0));
console.log(timeDifference(date2, 8, 0));
<script src="http://momentjs.com/downloads/moment.js"></script>
Essentially what you need to do is, once you have the end dates, create a new moment with the same date but your opens
start time. Then do the difference.
Or, you could also subtract:
let opens = "08:00";
let date1 = moment(new Date('1945.10.20 17:30'));
let date2 = moment(new Date('1970.01.08 12:00'));
function timeDifference(opens, end) {
// get the start
var start = moment(opens, "HH:mm");
// find how many minutes from midnight the start is
var startFromMidnight = start.diff(start.clone().startOf("day"), "minutes");
// find how many minutes from midnight the end is
var endFromMidnight = end.diff(end.clone().startOf("day"), "minutes");
// subtract the two to find the difference
return endFromMidnight - startFromMidnight;
}
console.log(timeDifference("08:00", date1));
console.log(timeDifference("08:00", date2));
<script src="http://momentjs.com/downloads/moment.js"></script>
Upvotes: 0
Reputation: 930
If I am reading this correctly, you want to compare the hours on your date object to 8AM.
Javascript has getHours() and getMinutes() from date object.
Hence you can do date.getHours() - 8, and date1.getMinutes()
Upvotes: 0