[removed] parse a string to Date as LOCAL time zone

后端 未结 3 1951
南旧
南旧 2020-11-27 18:14

I have a string representing the current time: 2015-11-24T19:40:00. How do I parse this string in Javascript to get a Date represented by this string as the

3条回答
  •  情深已故
    2020-11-27 19:09

    Where Date is called as a constructor with more than one argument, the specified arguments represent local time.

    I also have a much faster way than using the string.split() because we already know where the numbers are:

    return new Date(Number(date.substring(0, 4)), Number(date.substring(5, 7))-1, 
                    Number(date.substring(8, 10)), Number(date.substring(11, 13)), 
                    Number(date.substring(14, 16)), Number(date.substring(17, 19)));
    

    This will work with and/or without the 'T' and 'Z' strings and still has decent performance. I added the explicit Number conversion (faster and better than parseInt) so this also compiles in TypeScript. Number

提交回复
热议问题