My code is this:
const nowDate = moment(new Date()).format("DD/MM/YYYY");
let paraRepDate = '01/01/2021';
let calcParaDate = '30/06/2021';
var x = moment(calcParaDate).isBefore(nowDate)
console.log(x) // false
How is it possible?
CodePudding user response:
Default format of momentjs is MM/DD/YYYY
. In your solution you can see warning information in console:
Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Solution
You have to specify format moment(date, format)
. Something like this:
const format = 'DD/MM/YYYY';
const nowDate = moment();
const calcParaDate = '30/06/2021';
const isBefore = moment(calcParaDate, format).isBefore(nowDate)
console.log(isBefore);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment-with-locales.min.js" integrity="sha512-LGXaggshOkD/at6PFNcp2V2unf9LzFq6LE sChH7ceMTDP0g2kn6Vxwgg7wkPP7AAtX lmPqPdxB47A0Nz0cMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Also you don't have to pass new Date()
in moment()
for current datetime.
CodePudding user response:
If you were to read the deprecation warning that moment js is giving you, you would know that the date in said format cannot be passed as an argument to moment constructor as it is not a recognized RFC2822 or ISO format.
Calling moment with such a function will simply return null. And in turn calling isBefore
on null date will always return false. See snippet below for demonstration.
const theFallbackDate = moment('30/06/2021');
console.log({theFallbackDate}); // {theFallbackDate: null}
console.log(moment('30/06/2021').isBefore('30/06/2021')); // always full since calling isBefore on null date
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>