从 momentjs 中删除弃用警告



我正在使用momentjs来处理项目中的日期,当用户以M/D/YYYY格式输入日期以恢复为MM/DD/YYYY格式时(例如 2/5/201702/05/2017(。我还正在转换任何无效日期或大于今天的日期,以重置回今天的日期。

element.on("blur", function() {
    var currentDate = moment().format('MM/DD/YYYY');
    var formattedInput;
    if (ctrl.$modelValue !== undefined && ctrl.$modelValue !== "") {
        if(moment(ctrl.$modelValue, "MM/DD/YYYY", true).isValid()) {
            formattedInput = moment(ctrl.$modelValue);
            formattedInput.format('MM/DD/YYYY');
            if (formattedInput.isAfter(currentDate)) {
                ctrl.$setViewValue(currentDate);
                ctrl.$render();
            }
        } else if (moment(ctrl.$modelValue, "M/D/YYYY", true).isValid()) {
            formattedInput = moment(ctrl.$modelValue);
            formattedInput.format('MM/DD/YYYY');
            if (formattedInput.isAfter(currentDate)) {
                ctrl.$setViewValue(currentDate);
                ctrl.$render();
            } else {
                ctrl.$setViewValue(formattedInput.format('MM/DD/YYYY'));
                ctrl.$render();
            }
        } else {
            ctrl.$setViewValue(currentDate);
            ctrl.$render();
        }
    }
});

据我所知,这都可以使用我上面的代码正常工作。但无论工作功能如何,我都收到非 ISO 日期的弃用警告。我的想法是使用MM/DD/YYYY格式,但由于业务需求,这是不可更改的。有没有办法以不繁琐的方式解决这个问题?

问题在于formattedInput = moment(ctrl.$modelValue)在这里您使用没有非 ISO 日期格式的时刻解析。要删除弃用警告,只需像在if条件下一样使用 moment(ctrl.$modelValue, "MM/DD/YYYY")moment(ctrl.$modelValue, "M/D/YYYY")

您的完整代码如下:

element.on("blur", function() {
  var currentDate = moment();
  var formattedInput;
  if (ctrl.$modelValue !== undefined && ctrl.$modelValue !== "") {
    if(moment(ctrl.$modelValue, "MM/DD/YYYY", true).isValid()) {
      formattedInput = moment(ctrl.$modelValue, "MM/DD/YYYY", true);
      // This line returns a string, but does not assign to value, so it's superfluous
      //formattedInput.format('MM/DD/YYYY');
      if (formattedInput.isAfter(currentDate)) {
         ctrl.$setViewValue(currentDate.format('MM/DD/YYYY'));
         ctrl.$render();
      }
    } else if (moment(ctrl.$modelValue, "M/D/YYYY", true).isValid()) {
      formattedInput = moment(ctrl.$modelValue, "M/D/YYYY", true);
      // see previous comment
      //formattedInput.format('MM/DD/YYYY');
      if (formattedInput.isAfter(currentDate)) {
        ctrl.$setViewValue(currentDate.format('MM/DD/YYYY'));
        ctrl.$render();
      } else {
        ctrl.$setViewValue(formattedInput.format('MM/DD/YYYY'));
        ctrl.$render();
      }
    } else {
      ctrl.$setViewValue(currentDate.format('MM/DD/YYYY'));
      ctrl.$render();
    }
  }
});

请务必完全了解矩解析(从字符串构建矩对象(和矩format(显示矩对象的字符串表示形式(之间的区别。

相关内容

最新更新