31st date showing invalid date when using moment - javascript

I am finding the difference between 2 dates in years, but when I select the 31st date it shows an invalid date so the difference is NaN.
When I use other dates it shows the correct result.
const selectedValue = moment('31-8-2022');
const today = moment();
const yearDiff = today.diff(selectedValue, "year");
console.log(yearDiff);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

When running sample code you provided, a deprecation warning is raised:
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 and will be removed in an upcoming major
release. Please refer to
http://momentjs.com/guides/#/warnings/js-date/ for more info.
By inputing the date in ISO format, the code works:
const selectValue = moment('2022-08-31'); // 2022-08-31 instead of 31-8-2022
const today = moment();
const yearDiff = today.diff(selectValue, "year");
console.log(yearDiff);

when you use 'DD-MM-YYYY' in momentjs you get invalid date format.
const selectedValue = moment('30-08-2022').format('DD-MM-YYYY');
console.log(selectedValue)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
In order to make it valid date, you'll add 'DD-MM-YYYY' in the moment second paramater after the date and format it.
const selectedValue = moment('30-08-2022','DD-MM-YYYY').format('DD-MM-YYYY');
console.log(selectedValue)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
In instance you really have to use 'DD-MM-YYYY' in your code without the worry of depreciation warning. You could do this
const selectedValue = moment('30-08-2022', 'DD-MM-YYYY').format('DD-MM-YYYY');
console.log(selectedValue)
const today = moment().format('DD-MM-YYYY');
console.log(today)
const yearDiff = moment(today, 'DD-MM-YYYY').diff(moment(selectedValue, 'DD-MM-YYYY'), 'years');
console.log(yearDiff);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

Related

Comparing date and time with moment js

In my react app I am receiving an endDate, and also separately receiving an endTime. I have to check if that endDate and endTime are before the current date and time.
let endDate = "04/13/2022";
let endTime = "22:00"
console.log(moment(endDate, "MM/DD/YYYY", endTime).isBefore(moment());
//true
Today's date is the same as the endDate but the time is earlier than the endTime so I should see False instead of true. The times are not being compared. Does anyone know how to resolve this?
Combine the date and time strings, and parse as one full date-time string.
const endDate = '04/13/2022';
const endTime = '22:00';
const date = moment(`${endDate} ${endTime}`, 'MM/DD/YYYY HH:mm');
console.log(date.isBefore(moment())); // false
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.2/moment.min.js"></script>

date comparison moment js

I want to compare two dates and my date format is DD-MM-YYYY but I don't know why my output returns false when I compare my dates.
example 1
const date1 = '30-06-2021';
const date2 = '10-01-2022';
const result = moment(date1) < moment(date2); // return false, should return true
example 2
const date1 = '30-06-2021';
const date2 = '10-01-2022';
const result = moment(date1).isBefore(date2); // return false, should return true
There are two issues there:
You're expecting moment to guess the format of your dates, but it can't do that reliably. Always provide a format string if your string isn't in a RFC2822 or ISO-8601 format. moment itself warns you about doing that in the dev version of the library:
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/
< cannot be used to meaningfully compare objects. If you want to know if a date is before another date, use the isBefore method.
For example:
const date1 = "30-06-2021";
const date2 = "10-01-2022";
const format = "DD-MM-YYYY";
const result = moment(date1, format).isBefore(moment(date2, format));
const date1 = "30-06-2021";
const date2 = "10-01-2022";
const format = "DD-MM-YYYY";
const result = moment(date1, format).isBefore(moment(date2, format));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

How to check if today and specific date is same using moment

I want to check if today and a specific date is same using moment.
const today = moment(new Date()).format('DD/MM/YYYY')
console.log(today) // "28/09/2021"
const expiry = moment(new Date('2021/09/28')).format('DD/MM/YYYY')
console.log(expiry) // "28/09/2021"
Now When I compare , I am getting false
console.log(moment(today).isSame(expiry)); // false
It also showing me this in fiddle,
"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 and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Arguments:
You can compare it directly by operator ==
const today = moment(new Date()).format('DD/MM/YYYY')
console.log(today) // "28/09/2021"
const expiry = moment(new Date('2021/09/28')).format('DD/MM/YYYY')
console.log(expiry) // "28/09/2021"
console.log(today == expiry);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
const today = moment(new Date()).format('DD/MM/YYYY')
console.log(today) // "28/09/2021"
const expiry = moment(new Date('2021/09/28')).format('DD/MM/YYYY')
console.log(expiry) // "28/09/2021"
It's because here, you're setting today and expiry to strings, eg "21/12/2021"
and then asking moment to come strings when it's expecting dates.
Also need to add the flag 'day' to isSame
Try this instead
const today = moment(new Date());
console.log(today.format('DD/MM/YYYY')) // "28/09/2021"
const expiry = moment(new Date('2021/09/28'));
console.log(expiry.format('DD/MM/YYYY'));
console.log(moment(today).isSame(expiry, 'day'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Get timestamp from date string without timezone and timezone name apart

I have a dateTime string in this (bad, I know) format coming from an external API:
const startDate = '2/13/2020 15:00';
and the timezone name:
const timezoneName = 'America/New_York';
Which means that the dateTime is 2/13/2020 15:00 in New York.
Any idea for an elegant way to get timestamp (or JavaScript date object)?
I don't mind using moment.js or/and moment-timezone if it helps.
Moment and Moment-Timezone are for legacy code.
For new applications, the Moment team recommends Luxon.
const startDate = '2/13/2020 15:00';
const timezoneName = 'America/New_York';
const dateTime = luxon.DateTime.fromFormat(startDate, 'M/d/yyyy HH:mm',
{ zone: timezoneName });
const utcDateTime = dateTime.toUTC();
const s = utcDateTime.toISO();
console.log(s); //=> "2020-02-13T20:00:00.000Z"
Using moment-timezone should work:
const moment = require('moment-timezone');
const t = moment.tz("2/13/2020 15:00", "MM/DD/YYYY HH:mm","America/New_York");
console.log(t.toISOString()); // Prints '2020-02-13T20:00:00.000Z'

moment timezone returns bad value for unit test

So my project is using moment timezone. And it works perfectly everywhere its used except in a unit test. And I can't figure out why.
I'm calling
moment(new Date(date)).tz(timezone).format(mask);
where the date, mask, and timezone are as follows:
date = "2016-11-11T19:34:56.601Z"
mask = "mm-dd-yyyy"
timezone = "America/New_York"
The result I get is: 34-Fr-yyyy
In another call, the following occurs:
date = "2016-12-13T21:57:53.336Z"
mask = "mm-dd-yyyy"
timezone = "America/New_York"
and the result is 57-Tu-yyyy
You use the wrong date format, the correct is MM-DD-YYYY.
var date = "2016-12-13T21:57:53.336Z";
var mask = "mm-dd-yyyy";
var timezone = "America/New_York";
var dateStr = moment(date).tz(timezone).format('MM-DD-YYYY');
console.log(dateStr);
<script src="http://momentjs.com/downloads/moment.js"></script>
<script src="http://momentjs.com/downloads/moment-timezone-with-data.js"></script>
http://momentjs.com/docs/#/parsing/string-format

Categories

Resources