0

I have a date selector and a time selector, and I'm trying to figure out how I can combine their outputs to make a single ISOString so that I can use with the google calendar API. Here's what I've tried:

//date = 2022-05-18
//time = 14:22

const apptdate = new Date(date)
const timeSplit = time.split(':')
apptDate.setHours(timeSplit[0])
apptDate.setMinutes(timeSplit[1])

What I notice is when I console.log(apptdate) this is the output I get: 2022-05-17T18:22:00.000Z

I'm not sure why it changes the day from May 18 to May 17, and the time from 14:22 to 18:22. Does anyone have a solution for this? Or even a completely different way of combining date and time to one string (other than using a datetime-local input format, I want to keep the date and time separate in my database).

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Cip
  • 93
  • 7
  • 2
    Why not just string concatenation? `date + 'T' + time + 'Z'` (if the date and time are already in ISO format). – Heretic Monkey May 10 '22 at 19:42
  • The `Date` object assumes dates and times are local unless told otherwise; see [Is the Javascript date object always one day off?](https://stackoverflow.com/q/7556591/215552) – Heretic Monkey May 10 '22 at 19:45
  • That's Heretic Monkey, this was an easy solution, I just didn't think of it (new to javascript). Much appreciated :) – Cip May 11 '22 at 18:55

1 Answers1

1

"2022-05-18" is parsed as UTC but apptDate.setHours(timeSplit[0]) sets the local hour. So if the host has a negative offset, the local date is 17 May and the time is set to the local hour on 17 May, not UTC hour on 18 May.

Instead use setUTCHours and setUTCMinutes.

let date = '2022-05-18';
let time = '14:22';

let apptDate = new Date(date);
let timeSplit = time.split(':');
apptDate.setUTCHours(timeSplit[0]);
apptDate.setUTCMinutes(timeSplit[1]);

// 2022-05-18T14:22:00.000Z
console.log(apptDate.toISOString());

PS. There was also a typo: let apptdate then later apptDate.

RobG
  • 142,382
  • 31
  • 172
  • 209
  • Thank you for this info! I didn't even know setUTFHours was a thing (still learning). – Cip May 11 '22 at 16:02