I am using this simple function to get YYYYMMDD format:
const yyyymmdd = (date) => {
const day = date.getDate()
const month = date.getMonth() + 1
const year = date.getFullYear()
console.log(date, day)
let dayZero = (day < 10) ? "0" + day : day
let monthZero = (month < 10) ? "0" + month : month
return year + "-" + monthZero + "-" + dayZero
}
Note the console.log that prints the date and day.
The output for several calls of different dates are:
2020-10-18T06:36:31.116Z 18
2020-10-19T06:36:31.116Z 19
2020-10-20T06:36:31.116Z 20
2020-10-21T06:36:31.116Z 21
2020-10-22T06:36:31.116Z 22
2020-10-23T06:36:31.117Z 23
2020-10-24T06:36:31.117Z 24
2020-10-15T22:58:36.021Z 16
2020-10-15T22:58:36.021Z 16
2020-10-15T22:58:36.021Z 16
2020-10-15T22:58:36.021Z 16
2020-10-16T22:58:36.021Z 17
The last 5 results have inaccurate day for the format. The ones correct above are built with the following function and gives the expected results:
return new Date(new Date().getTime() + i * 24 * 60 * 60 * 1000)
But the ones that are wrong, are from MongoDB stored as a string and then converted to date as following:
new Date(mongo_db_string_date)
Can anyone help me understand why this happens? They seem to be the same date format, but may not be. How can I parse to get the right result?