Reputation: 1219
I am trying to validate a date in string format with moment JS.
I use the dd/mm/yy
format in pCalendar in ngPrime and the stDate
is the value I get.
Here is my code snippet:
var stDate = '02/02/2021';
var stDateMoment = moment(stDate, 'dd/mm/yy');
I can not understand why the expression
stDateMoment.isValid()
returns a false value.
Any ideas or suggestions?
Thank you!
Upvotes: 0
Views: 72
Reputation: 4122
You are very almost there. The format tokens are case-sensitive, so using the lowercase dd
, mm
, and yy
is not valid.
const stDate = '02/02/2021';
const stDateMoment = moment(stDate, 'DD/MM/YYYY');
console.log(
stDateMoment.isValid()
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
For more information on this, please read the momentjs string format documentation.
The docs also state that two Y
s is for two-digit years, but four Y
s is for four-digit years.
Upvotes: 1
Reputation: 418
creating a Date Object for your formatted date will solve the issue
var stDate = new Date("02/02/2021");
var stDateMoment = moment(stDate,"DD/MM/YY");
const validation = stDateMoment.isValid(); // true
Upvotes: 0