0

JavaScript is determined to ensure I get the wrong date.

I have UTC dates from the server. If I take the first one, it looks like this: 2021-03-09 19:00:00.

My chart takes a date object. So I want to convert from UTC. The correct answer is:

-Tue Mar 09 2021 12:00:00 GMT-0700 (Mountain Standard Time)

Here is an insane overcoded attempt to force the right answer:

// given inputDate from the server
let re: RegExp = /{regular expression parsing date}/;
let m: RegExpMatchArray = inputDate.match(re);
let yyyy: number = Number(m[1]); // 2021
let mm: number = Number(m[2]);   // 3
let dd: number = Number(m[3]);   // 9
let hh: number = Number(m[4]);   // 19
let utc: number = Date.UTC(yyyy, mm, dd, hh);
let utcDate: Date = new Date(utc);

console.log('interp', `${yyyy}-${mm}-${dd} ${hh}:00:00`);
console.log('utcDate', utcDate.toISOString());

Result:

interp 2021-3-9 19:00:00
utcDate 2021-04-09T19:00:00.000Z

Am I going insane? Why did it add a month??

Moment works so I guess I can stomach the extra 70KB:

let tryUtc: Moment = moment(inputDate).utc(true);
console.log('local', tryUtc.toDate());   // bingo

I still want to know why the month got added.

AndrewBenjamin
  • 651
  • 1
  • 7
  • 16
  • 2
    Does this answer your question? https://stackoverflow.com/a/12254344/14909805 – BurdenKing Apr 07 '21 at 00:25
  • @BurdenKing Yes it does and there's a very special place in hell for the person who decided to start months at 0. Why not start days, years, hours, minutes at zero too? Then everything can be wrong. – AndrewBenjamin Apr 07 '21 at 00:30
  • 3
    @AndrewBenjamin some background can be found here if you're curious ~ https://stackoverflow.com/questions/2552483/why-does-the-month-argument-range-from-0-to-11-in-javascripts-date-constructor – Phil Apr 07 '21 at 00:33
  • 1
    Parsing "2021-03-09 19:00:00" as UTC is 2 lines of code, you seriously do not need a library for that (e.g. `let [Y,M,D,H,m,s] = "2021-03-09 19:00:00".split(/\D/); let date = new Date(Date.UTC(Y,M-1,D,H,d,s))`. – RobG Apr 07 '21 at 00:35

0 Answers0