Home > Mobile >  JS Date not correct
JS Date not correct

Time:02-04

I have some troubles with JS Dates.

I´m passing a Date to a Function in which I try to parse it to a Date object. However this is not working on some Dates.

Example: I pass 31.01.2022 to this function create a new Date object and set Day/Month etc. If I print out the Date afterwards it states January 3rd.

What I am missing here?

Code:

const [editedHours, setEditedHours] = useState([])

//ChangeHandler Input Field
const postHours = (e, entry_id, index, date) => {
    let newArr = [...editedHours]
    newArr[index] = {
        entry_id: entry_id,
        date: date, //format dd.mm.yyyy
        time: e.target.value //format HH:MM
    }
    setEditedHours(newArr)
}

const pushHours = () => {
    let pushHoursArr = []
    for(let i = 0; i < editedHours.length; i  ) {
        let hour = editedHours[i].time.substr(0, 2) //getHour
        let minute = editedHours[i].time.substr(3, 2) //getMinute
        let dateStr = editedHours[i].date.split(".") //Split 31.01.2022
        const date = new Date();
        date.setDate(dateStr[0]) //31
        date.setMonth(dateStr[1] -1) //Month 01 -1 since Month starts at 0
        date.setFullYear(dateStr[2]) //2022
        date.setHours(hour)
        date.setMinutes(minute)
        date.setSeconds(0)

        console.log(date) //prints out Mon Jan 03....

        pushHoursArr.push({
            entry_id: editedHours[i].entry_id,
            date: date
        })
    }

CodePudding user response:

The issue here is the order of your work:

First you set the date to now, but your existing date is today (February, which only has 28 days)

So, setting a date in Feb to 31, wraps around to the 3rd.

const example = '31.01.2022'

let dateStr = example.split(".")
const date = new Date();
date.setDate(dateStr[0])
date.setMonth(dateStr[1] - 1)
date.setFullYear(dateStr[2])
console.log(date)

To show how this affects the result, this is what happens if you set the year, then month, then day:

const example = '31.01.2022'

let dateStr = example.split(".")
const date = new Date();
date.setFullYear(dateStr[2])
date.setMonth(dateStr[1] - 1)
date.setDate(dateStr[0])
console.log(date)

The best option is to construct the date all at once:

new Date(year, month, day, hours, minutes)

const example = '31.01.2022'

let dateStr = example.split(".")
const date = new Date(dateStr[2], dateStr[1] - 1, dateStr[0])
console.log(date)

  •  Tags:  
  • Related