0

Suppose I create an all day event for Christmas day. I want this event to be 25 Dec regardless of which timezone you are in. I store the event date as "2023-12-25" on the server.

When I do new Date("2023-12-25") in the browser it's interpreted as a UTC date which is not what I want, for example if I'm in New York and I do

new Date("2023-12-25") // Sun Dec 24 2023 19:00:00 GMT-0500 (Eastern Standard Time)

Which means when I go to format the all day event it will format as 24 December which is not what I want.

Desired behaviour:

// If in New York
parseAllDayDate("2023-12-25") // Sun Dec 25 2023 00:00:00 GMT-0500 (Eastern Standard Time)

// If in London
parseAllDayDate("2023-12-25") // Mon Dec 25 2023 00:00:00 GMT+0000 (Greenwich Mean Time)

Also, please don't suggest dayjs or momentjs I would like to do this just with JS Date.

Zoe
  • 27,060
  • 21
  • 118
  • 148
david_adler
  • 9,690
  • 6
  • 57
  • 97
  • The calls to *Number* in the last line are redundant, `return new Date(year, month - 1, day)` is sufficient. – RobG Apr 04 '22 at 13:08
  • Oh the wonders of javascript @RobG of course `"02" - 1 === 1` – david_adler Apr 05 '22 at 08:56
  • 1
    Sure, but when the [*Date* constructor](https://262.ecma-international.org/#sec-date) is called with two or more arguments, then *ToNumber* is called on each argument, so doing it manually is, literally, redundant. ;-) – RobG Apr 05 '22 at 11:02

1 Answers1

-2

You can try this

parseAllDayDate(dateString) {
    let dateStringSplit = dateString.split('-');
    let date = new Date();
    date.setUTCDate(dateStringSplit[2]);
    date.setUTCMonth(dateStringSplit[1]);
    date.setUTCFullYear(dateStringSplit[0]);
    return date;
}
viltor
  • 331
  • 1
  • 7
  • Mixing local and UTC methods as in this answer is fraught and bound to introduce errors, e.g. mock running this on 28 Feb and pass it a date for 31 Jan. – RobG Apr 01 '22 at 10:30