【问题标题】:Moment.js time comparingMoment.js 时间比较
【发布时间】:2018-12-16 11:16:05
【问题描述】:

我使用Vue.jsMoment.js 库来处理时间,我需要比较小时和分钟,而不是日期。比如我需要比较'12:00''13:45',我使用.isBefore函数(docs)。

我尝试了一堆函数,它们可以处理日期,但不准确(我尝试了很多示例,所以这是最后一个)

我用moment做原型,所以$就可以了

let time = this.$moment('10:00-11:30'.split('-')[0], 'HH:mm').format('HH:mm');
let time2 = this.$moment(new Date(), 'HH:mm').format('HH:mm');
console.log({time, time2});
console.log(this.$moment(time.format('hh:mm').isBefore(this.$moment('12:00'), 'hh:mm'))
console.log(this.$moment(time, 'hh:mm').format('hh:mm').isBefore(this.$moment(time2).format('hh:mm'), 'hh:mm'))
console.log(this.$moment(this.$moment('10:00', 'HH:mm').format('HH:mm')).isBefore(this.$moment('12:00'),'HH:mm'));
console.log(this.$moment(this.$moment('10:00', 'HH:mm').format('HH:mm')).isBefore(this.$moment(time2).format('HH:mm'),'HH:mm'));

其中一些返回false,但应该返回true,其中一些返回错误.isBefore is not a function。 我还找到了thisthisthis,但它只适用于确切的日期,而不仅仅是小时和分钟

谁能帮我弄清楚我做错了什么?

【问题讨论】:

    标签: vue.js momentjs


    【解决方案1】:

    您的代码示例中有几个问题,首先format() 返回一个字符串,因此您不能在time.format('hh:mm') 之类的东西上使用isBefore,这就是您得到isBefore is not a function 的原因

    此外,即使您通过仅提供时间值来创建时刻对象,时刻对象也始终表示给定时刻(日期 + 时间)。正如文档的Defaults 部分所述:

    您可以创建仅指定部分单位的矩对象,其余的将默认为当前日、月或年,或 0 表示小时、分钟、秒和毫秒。

    我建议使用format()(不带参数)来检查你的时刻对象的值,以更好地理解为什么你会得到意想不到的结果。

    这里是您的代码示例的未更新版本(没有 vue.js),以展示如何使用 isBefore

    let time = moment('10:00-11:30'.split('-')[0], 'HH:mm');
    let time2 = moment();
    console.log( time.format(), time2.format() );
    console.log( time.isBefore(moment('12:00', 'hh:mm')) );
    console.log( time.isBefore(time2) );
    console.log( moment('10:00', 'HH:mm').isBefore(moment('12:00','HH:mm')) );
    console.log( moment('10:00', 'HH:mm').isBefore(time2) );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

    【讨论】:

      猜你喜欢
      • 2012-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多