【问题标题】:Moment.js isBefore() not working when checking for if before 12pm/NoonMoment.js isBefore() 在检查是否在中午 12 点/中午之前不起作用
【发布时间】:2019-02-04 20:30:39
【问题描述】:

我正在使用 Moment.js 在前端处理一些日期标签。我遇到了一个晦涩难懂的场景,希望 MomentJS 专家能够纠正我的问题。

考虑下面的实现,传入一个字符串值"2018-08-28T20:21:56"

请注意,上述日期字符串和添加分钟600 是从后端动态提供的。

let dateTitle;

// Before setting date label, compare enddate with endoffset against 12pm
let endCutOff = moment("2018-08-28T20:21:56").add(600, 'm');
let isBeforeNoon = moment(endCutOff).isBefore(moment({ hour: 12, minute: 0 }));

if ( isBeforeNoon ) {
    // Credit previous day if user ended before noon.
    dateTitle = moment("2018-08-28T20:21:56")
    .add(600, 'm')
    .local()
    .subtract(1, 'd')
    .format('MMMM D, YYYY');
} else {
    // Credit that very day if after 12pm.
    dateTitle = moment("2018-08-28T20:21:56")
    .add(600, 'm')
    .local()
    .format('MMMM D, YYYY');
}

这会正确输出为 "August 28, 2018"

但是,使用传入的字符串值 "2018-08-29T20:43:58" 再次执行相同的操作,您会看到输出为 "August 30, 2018"

应该是“2018 年 8 月 29 日”

我认识到isBeforeNoon 第一轮为真,下一轮为假这一点很明显。但是,我需要您的专业知识来解释为什么以及如何解决它。我怀疑它与传递的日期字符串格式有关,但到目前为止这只是一个概念。

感谢您的帮助。

【问题讨论】:

    标签: javascript date datetime momentjs


    【解决方案1】:

    如果我对情况的理解正确,问题是由moment({ hour: 12, minute: 0 }) 的日期部分默认为“今天的日历日期”引起的。

    默认情况下,.isBefore() 同时考虑比较时刻实例的时间和日期

    因此,这意味着isBeforeNoon 是根据endCutOff 的日期和当前日历日期(显然总是在变化)决定的。

    也许您可以执行以下操作:

    let endCutOff = moment("2018-08-28T20:21:56").add(600, 'm');
    
    // Create a copy of endCutOff to aquire the date from endCutOff, and set
    // hour/minute accordingly
    let momentForIsBefore = endCutOff.clone().hour(12).minute(0).second(0); 
    let isBeforeNoon = moment(endCutOff).isBefore(momentForIsBefore);
    
    if ( isBeforeNoon ) {
        // Credit previous day if user ended before noon.
        dateTitle = moment("2018-08-28T20:21:56")
        .add(600, 'm')
        .local()
        .subtract(1, 'd')
        .format('MMMM D, YYYY');
    } else {
        // Credit that very day if after 12pm.
        dateTitle = moment("2018-08-28T20:21:56")
        .add(600, 'm')
        .local()
        .format('MMMM D, YYYY');
    }
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-13
      • 1970-01-01
      • 2016-01-13
      • 2011-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多