如何处理moment.js中的弃用警告 [英] how to handle deprecation warning in momentjs
问题描述
我想使用momentjs来检查无效的日期/时间字符串:
I want to use momentjs to check for invalid date/time strings:
var invalid = '2017-03-18 23;00;00';
if (moment(invalid).isValid()) {
return 'valid date'
}
这(正确)抛出带有熟悉的弃用警告:所提供的值不是公认的RFC2822或ISO格式......"的堆栈跟踪信息.
This (correctly) throws a stacktrace with the familiar 'Deprecation warning: value provided is not in a recognized RFC2822 or ISO format......'
但是即使我添加了try/catch:
But even if I add a try/catch:
try {
var invalid = '2017-03-18 23;00;00';
if (moment(invalid).isValid()) {
return 'valid date'
}
catch (err) {
throw Error ('invalid date format');
}
仍然显示堆栈跟踪. 我该怎么做才能避免显示堆栈跟踪记录?
the stacktrace is still printed. What do I need to do to avoid the stacktrace from being printed?
我已经在StackOverflow上搜索了所有类似的问题,但是它们都试图解决一个不同的问题(修复输入或找到正确的语法来解析输入).
I've searched all similar questions on StackOverflow but they all try to solve a different problem (fixing the input or finding the correct syntax to parse the input).
我使用的是v2.18.1.
I using v2.18.1.
推荐答案
您必须使用 moment(String, String);
来解析您的输入.如果您不想指定格式(或格式数组 ),则可以使用 moment.ISO_8601
.正如文档所说:
You have to use moment(String, String);
to parse your input. If you don't want to specify a format (or an array of formats), you can use moment.ISO_8601
. As the docs says:
Moment已经支持解析iso-8601字符串,但是在构造矩时可以在格式/格式列表中明确指定
Moment already supports parsing iso-8601 strings, but this can be specified explicitly in the format/list of formats when constructing a moment
这样,您将不会收到过时警告.这是一个工作示例:
This way you will not have deprecation warning. Here a working example:
var invalid = '2017-03-18 23;00;00';
if (moment(invalid, moment.ISO_8601).isValid()) {
console.log('valid date');
} else {
console.log('invalid date');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
PS.无论如何,如果您有可接受格式的列表,我建议使用moment(String, String[]);
(如果需要,还可以使用严格解析).
PS. Anyway, if you have a list of accepted format, I suggest to use moment(String, String[]);
(and strict parsing, if needed).
这篇关于如何处理moment.js中的弃用警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!