Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to handle deprecation warning in momentjs

Tags:

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' } 

This (correctly) throws a stacktrace with the familiar 'Deprecation warning: value provided is not in a recognized RFC2822 or ISO format......'

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?

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).

I using v2.18.1.

like image 658
hepabolu Avatar asked Mar 29 '17 18:03

hepabolu


People also ask

Is MomentJS being deprecated?

Moment construction falls back to js Date. This is discouraged and will be removed in an upcoming major release. This deprecation warning is thrown when no known format is found for a date passed into the string constructor.

Is MomentJS outdated?

MomentJs recently announced that the library is now deprecated. This is a big deal for the javascript community who actively downloads moment almost 15 million times a week. With that I began a journey during a Hackathon to replace moment in a core library at my company.

How do I get current year in MomentJS?

Calling format('YYYY') will invoke moment's string formatting functions, which will parse the format string supplied, and build a new string containing the appropriate data. Since you only are passing YYYY , then the result will be a string containing the year. If all you need is the year, then use the year() function.


1 Answers

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 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. Anyway, if you have a list of accepted format, I suggest to use moment(String, String[]); (and strict parsing, if needed).

like image 169
VincenzoC Avatar answered Sep 19 '22 12:09

VincenzoC