Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strictly parsing dates with moment

When you create a moment from a date string and pass in the format, moment very loosely checks the date string against the format. for example the following dates are all valid

moment('1','YYYY-MM-DD').isValid() //true
moment('1988-03','YYYY-MM-DD').isValid() //true
moment('is a val1d date!?#!@#','YYYY-MM-DD').isValid() //true

Is there any way to only accept dates that match the specified format?

like image 395
rob Avatar asked Mar 09 '16 17:03

rob


People also ask

How can I get only the date from datetime using moments?

We can use the startOf method to return a moment date object without the time portion of a date. Also, we can use the format method to return a date string without the time portion of a date.

How do you compare dates with moments?

Compare two dates using Moment.js has a diff() method, which gives the difference between two dates in years, months, days, hours, minutes, seconds, milliseconds, etc. We can use the second unit in our case to find the difference between the two dates.

How do I change a moment date to a specific format?

Date format conversion with Moment is simple, as shown in the following example. moment(). format('YYYY-MM-DD'); Calling moment() gives us the current date and time, while format() converts it to the specified format.

Is MomentJS deprecated?

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.


1 Answers

As of version 2.3.0, you may specify a boolean for the last argument to make Moment use strict parsing. Strict parsing requires that the format and input match exactly, including delimeters.

moment('It is 2012-05-25', 'YYYY-MM-DD').isValid();       // true
moment('It is 2012-05-25', 'YYYY-MM-DD', true).isValid(); // false

Found in this section of the Moment JS docs

like image 117
J. Titus Avatar answered Oct 02 '22 13:10

J. Titus