When I convert a string date to a date object, it’s getting the date wrong:
function formatDate(inputDateString) {
const date = new Date(inputDateString);
// Check if the date is valid
if (isNaN(date.getTime())) {
return "Invalid Date";
}
const month = String(date.getMonth() + 1).padStart(2, "0"); // Adding 1 because months are zero-based
const day = String(date.getDate()).padStart(2, "0");
const year = date.getFullYear();
return `${month}/${day}/${year}`;
}
var testDate = formatDate("1980-01-01");
console.log("testDate: " + testDate);
Result: 12/31/1979
At first I thought maybe my getXXX()
constructions were suspect, but in Chrome Dev Tools, the debugger is telling me that the moment I create the new Date()
object, it believes the date is 12/31/1979. I’m wondering about GMT/UTC type of stuff, but I believe that js date functions already take into account user’s time zone. I am in Mountain Time.
WTH?