Get difference between two times using vuetify time picker and momentjs

Viewed 156

I'm building a scheduling app, and I'm having trouble getting the difference between two times. One of the times is now, which I get using momentjs and the other time, which would be the user's departure time from a given place, using the vuetifyjs time picker. The purpose of getting these two times would be to calculate the time remaining between now and the hour of departure. So for example, if the current time, now, is 4PM on Wednesday and the departure time is 2PM on Thursday, the expected output is 22 hours. Now, I format each of the times like this:

let now = moment().format("HH");
let departureHour = moment(this.departureTime, "HH").format("HH");

When I look at the individual outputs of these variables, I see two strings, or moment instances, for example 'now': '16', 'departureHour': '14'. However, when I try to get their differences like this,

return departureHour.diff(now, "hours");

I get an error that says:

[Vue warn]: Error in render: "TypeError: departureHour.diff is not a function"

I've also tried formatting the variables like so

let now = moment.utc().format("HH");
let departureHour = moment.utc(this.departureTime, "HH").format("HH");

But I get the same error.

I've tried a couple of solutions I've found, like this one, this one, and this one, but none of them seem to be working for me.

Any help will be greatly appreciated. If there's anything else you'd need to know, let me know.

I hope my question isn't too rambling.

Thank you.

1 Answers

The error you get suggests that departureHour is not a moment object. It is a String

You might also get a calculation error since now is not in utc and departureHour is.

Final caveat, I am not what you expect departureHour to be initialize from.

If you are looking to see the difference between two moment objects, in hours:

const now = moment.utc();
const departureHour = moment.utc(this.departureTime, "HH");

const diff = departureHour.diff(now, "hours"));

If you just want the difference between two numbers, it might be better to use number subtraction:

const now = Number(moment.utc().format("HH"));
// assuming departure time is in "HH" format, a number between 00 to 24
const diff = Math.abs(Number(departureTime) - now);
Related