FeelinProggy / CPW204_Bookstore_OngoingPractice

A class example for ongoing GitHub and TypeScript practice.
https://feelinproggy.github.io/CPW204_Bookstore_OngoingPractice/
0 stars 0 forks source link

DatePicker is off by one day #5

Closed FeelinProggy closed 1 year ago

FeelinProggy commented 1 year ago

With the following code, there is a timezone issue that returns a date earlier than selected.

 // Validate Date
let releaseDate = releaseDateTextBox.value;
let releaseDateCheck = Date.parse(releaseDate);
if (isNaN(releaseDateCheck)) {
    isValidData = false;
    releaseDateTextBox.nextElementSibling!.textContent = "Please enter a valid date."
}
else {        
    releaseDateTextBox.nextElementSibling!.textContent = "";
}
// Once all data has been validated...
if (isValidData) {
    let addedBook = new Book;
    addedBook.isbn = isbn;
    addedBook.price = price;
    addedBook.title = title;
    addedBook.releaseDate = new Date(releaseDate);

    return addedBook;
}
else {
    return null;
}

image

FeelinProggy commented 1 year ago

Solution from ChapGPT- In this code, we split the releaseDate string into an array of strings ['year', 'month', 'day'], and then we use map(Number) to convert each string to a number. We then use these numbers to create a new Date object. Note that we subtract 1 from the month because the month argument in the Date constructor is zero-based (January is 0, February is 1, etc.).

This approach eliminates the need to use Date.parse and directly creates the Date object using the individual components of the date.

// Validate Date let [year, month, day] = releaseDateTextBox.value.split('-').map(Number); if (isNaN(year) || isNaN(month) || isNaN(day)) { isValidData = false; releaseDateTextBox.nextElementSibling!.textContent = "Please enter a valid date." } else {
releaseDateTextBox.nextElementSibling!.textContent = ""; }

// Once all data has been validated... if (isValidData) { let addedBook = new Book; addedBook.isbn = isbn; addedBook.price = price; addedBook.title = title; addedBook.releaseDate = new Date(year, month - 1, day); image