【问题标题】:Get difference between two times using vuetify time picker and momentjs使用 vuetify 时间选择器和 momentjs 获取两次之间的差异
【发布时间】:2021-08-12 22:04:33
【问题描述】:

我正在构建一个日程安排应用程序,但我无法确定两次之间的差异。一个时间是现在,我使用 momentjs 和另一个时间,这将是用户离开给定地点的时间,使用 vuetifyjs 时间选择器。获得这两个时间的目的是计算从现在到出发时间之间的剩余时间。例如,如果当前时间现在是星期三下午 4 点,出发时间是星期四下午 2 点,那么预期输出是 22 小时。现在,我像这样格式化每个时间:

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

当我查看这些变量的单个输出时,我会看到两个字符串或时刻实例,例如 'now': '16'、'departureHour': '14'。但是,当我尝试像这样了解他们的差异时,

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

我收到一条错误消息:

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

我也尝试过像这样格式化变量

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

但我得到了同样的错误。

我已经尝试了几个我找到的解决方案,例如 oneoneone,但它们似乎都不适合我。

任何帮助将不胜感激。如果您还有什么需要知道的,请告诉我。

我希望我的问题不会太漫无边际。

谢谢。

【问题讨论】:

    标签: javascript momentjs vuetify.js


    【解决方案1】:

    您收到的错误表明departureHour 不是时刻对象。这是一个String

    由于now 不在utc 中而departureHour 不在,您可能还会遇到计算错误。

    最后的警告,我不是你期望的 departureHour 被初始化的对象。

    如果您想查看两个矩对象之间的差异,以小时为单位:

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

    如果你只是想要两个数字之间的差异,最好使用数字减法:

    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-20
      • 1970-01-01
      • 1970-01-01
      • 2010-12-18
      • 2017-08-15
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多