date comparison moment js - javascript

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>

Related

31st date showing invalid date when using moment

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>

Use date-fns to format day as UTC

I have the following date format 2022-07-20 and I would like to parse into the following format 2022-07-20T00:00:00.000Z
I'm using the following code
const main = () => {
const day = '2022-07-20'
const date = new Date()
const result = parse(day.toString(), 'yyyy-MM-dd', date)
console.log(result.toISOString())
}
And getting the following output 2022-07-19T21:00:00.000Z. I assume this happening because my timezone is UTC+3.
How do I get it formatted as 2022-07-20T00:00:00.000Z?

Compare yyyy-mm-dd formatted date strings without the Date object possible?

If I define a date range using purely date strings in yyyy-mm-dd format, it appears comparison will work just fine without using the Date object:
const dateParts = '2021-12-15--2022-01-15'.split('--') // My date range
const startDate = dateParts.slice(0, 1) // '2021-12-15'
const endDate = dateParts.slice(1) // '2022-01-15'
const date = '2021-12-14'
// Test if date is within the range
console.log(date >= startDate && date <= endDate) // false
Using any date in the above example will test successfully if what I want is ensure that the date I'm looking for is within the range.
Why is this working? If javascript was, under the hood, evaluating the date strings as numbers, this should not be working. Is it maybe just implicitly assuming it's a date without me having to parse them using new Date(date)...?
Update: I'm not looking for solutions on how to do this using the Date object, I'd be more interested in examples where comparing dates this way would NOT work.
Your code works (Or if it looks like its working) because its just a basic string comparison and not the date comparison. To do a proper date comparison, you need to do the proper string to date conversion, and then compare them.
const dateParts = '2021-12-15--2022-01-15'.split('--') // My date range
const startDate = dateParts[0] // '2021-12-15'
const endDate = dateParts[1] // '2022-01-15'
const startDateArray = startDate.split("-").map(element => parseInt(element));
const endDateArray = endDate.split("-").map(element => parseInt(element));
const date = '2022-01-15'
const dateArray = date.split("-").map(element => parseInt(element));
// Test if date is within the range
console.log(new Date(dateArray[0], dateArray[1] - 1, dateArray[2]) >= new Date(startDateArray[0], startDateArray[1] - 1, startDateArray[2]) && new Date(dateArray[0], dateArray[1] - 1, dateArray[2]) <= new Date(endDateArray[0], endDateArray[1] - 1, endDateArray[2])) // false
This should solve your problem
const dateParts = '2021-12-15--2022-01-15'.split('--'); // My date range
const startDate = dateParts[1]; // '2021-12-15'
const endDate = dateParts[0]; // '2022-01-15'
const date = '2021-12-10'
// Test if date is within the range
alert(date < startDate && date < endDate)

Getting 'NaN' while trying to convert a string of date to milliseconds [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 2 years ago.
Tried this:
1.
const today = new Date('28.08.2020');
const milliseconds = today.getTime();
const today = Date.parse("28.08.2020")
var today = new Date('28.08.2020');
var milliseconds = today.getMilliseconds();
Getting NaN while trying to convert a string of date to milliseconds
Better to change date format to YYYY-MM-DD as suggested in other answer
Or you can do something like this
var from = '28.08.2020'.split(".");
var today = new Date(from[2], from[1] - 1, from[0]);
const milliseconds = today.getTime();
console.log(milliseconds);
You use the incorrect format. If you get the date from backend you should convert it.
const date = '28.08.2020';
const [day, month, year] = date.split('.');
const validDate = new Date();
validDate.setFullYear(year);
validDate.setDate(day);
validDate.setMonth(month);
// or just
const validDate2 = new Date(year, month, day);
const milliseconds = validDate.getTime();
const milliseconds2 = validDate2.getTime();
console.log(milliseconds)
console.log(milliseconds2)
After this conversion you can use the date as you want
Assuming that you do not want to manually parse the string, you could try to use moment library, which allows one to provide custom dateString patterns used for parsing the date, like demonstrated below
const dateString = '28.08.2020';
const date = moment(dateString, "DD.MM.YYYY");
console.log("date", date); // displayed zulu time might be different than your local timezone
console.log("milliseconds", date.valueOf());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
Please take a note that moment will accept the date in your local timezone, which may pose some issues. If you want to make up for it, you should look up moment-timezone library
Oh, in that case you can change the imput to the "yyyy-mm-dd", is that a posibility?
const date = '28.08.2020';
let dateFromat = date.split('.');
dateFromat = `${dateFromat[2]}-${dateFromat[1]}-${dateFromat[0]}`;
const today = new Date(dateFromat);
const milliseconds = today.getTime();
output: 1598572800000
the dating format is wrong.
new Date('2020-08-28') should work

Convert given timestamp to influxdb timestamp

My Incoming Date is in format : 15.08.2017 23:03:23.120000
Here I am using Node-Red Platform to convert msg.payload.time in Influx timestamp but I am getting this Error:
"Error: Expected numeric value for, timestamp, but got '15.08.2017 23:03:23.120000'!".
Please let me know the script for given timestamp to influxdb timestamp.
InfluxDB expects unix timestamps and msg.payload.time might be a string, hence you are getting the error.
In order to generate a timeStamp from a date, you can use the Date functionality of JS.
It works in the following way:
new Date('<your-date-string>').valueOf()
Here the date-string is expected in 'YYYY-MM-DD hh:mm:ssZ' format.
In your case, since the msg.payload.time is available in dd.mm.yy hh:mm:ssZ format, you will need to perform some additional operations.
You can update your code as below:
const incomingDate = msg.payload.time;
// extract the date dd.mm.yyyy from the incoming Date String
const splittedDate = incomingDate.split(' ');
// Convert the date from dd.mm.yyyy to yyyy-mm-dd format
let date = splittedDate[0].split('.').reverse().join('-');
// Store time value in a separate variable for later use.
const time = splittedDate[1];
// merge date and time to form yyyy-mm-dd hh:mm:ssZ format
const datetime = `${date} ${time}`
// assign the timestamp value to fields.time
fields.time = new Date(datetime).valueOf();
Here is a working example
const incomingDate = '15.08.2017 23:03:23.120000';
const splittedDate = incomingDate.split(' ');
let date = splittedDate[0].split('.').reverse().join('-');
const time = splittedDate[1];
const datetime = `${date} ${time}`
console.log(datetime);
console.log(new Date(datetime).valueOf())

Categories

Resources