The error you are encountering is because the new Date() constructor in JavaScript expects a date string in a specific format that it can parse correctly. The format you’re using, “23/07/2024 8:24 AM”, is not a format that new Date() can automatically parse.
To solve this, you can either reformat the date string to a format that new Date() can parse, or manually parse the date string and construct the date object. Here’s how you can do it manually:
Reformat the Date String: Convert the date string to a format that JavaScript can parse, such as “YYYY-MM-DDTHH:MM:SS”.
let dateStr = "23/07/2024 8:24 AM";
let parts = dateStr.split(/[/ :]/);
let day = parts[0];
let month = parts[1] - 1; // JavaScript months are 0-based
let year = parts[2];
let hour = parts[3];
let minute = parts[4];
let period = parts[5];
if (period === "PM" && hour != 12) {
hour = parseInt(hour) + 12;
} else if (period === "AM" && hour == 12) {
hour = 0;
}
let date = new Date(year, month, day, hour, minute);
console.log(date); // Outputs the correct date