首页 > 解决方案 > Moment onSameOrBefore 函数始终为假

问题描述

我正在使用时刻来验证日期输入,并且我遇到了 sameOrBefore 函数的问题。

这是我的代码:

    const today = moment().format("DD/MM/YYYY");
    const legal = moment({today}).subtract(18, 'years').format("DD/MM/YYYY");
    console.log('hoy',today);
    console.log('edad legal', legal);
    const before = moment(value).isSameOrBefore({legal});
    console.log('before',before);
    if (before === false){
        toastError('Ingrese una fecha valida');
        return;
    }

我的意见

<Form.Control 
      className="text-field" 
      type="string" 
      value={value}
      onChange={onChange}
      placeholder="Ingresá tu fecha de nacimiento" />

而且我正在尝试使用 2002 年之前的任何日期,即“合法”日期的值,并且无论我输入什么日期,该函数都返回 false。例如,我将 03/03/1990 作为值写入,isSameOrBefore 函数返回 false。

谁能帮我这个?

标签: javascriptreactjsmomentjs

解决方案


为 moment 对象添加正确的格式以计算差异。

这将为您完成工作。

let input = "10/01/2002";
let legal = moment().subtract(18, "years");
let result = moment(input, "DD/MM/YYYY").isSameOrBefore(legal);
console.log(result);
<script src="https://momentjs.com/downloads/moment.js"></script>


推荐阅读