最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript: ERROR RangeError: Invalid time value - Stack Overflow

programmeradmin2浏览0评论

Below is my code.

let a = "26-Jan-2021 06:02 PM PST";

let d = "27-Jan-2021 07:32 AM IST";

let b = new Date(a).toString();

let c = new Date(a).toISOString();

console.log(c);

let e = new Date(d).toISOString();

console.log(e);

OutPut:

"2021-01-27T02:02:00.000Z"

"Invalid time value"

Question: What is the difference between how JavaScript interprets variables a and d that it spits out such different outputs?

Below is my code.

let a = "26-Jan-2021 06:02 PM PST";

let d = "27-Jan-2021 07:32 AM IST";

let b = new Date(a).toString();

let c = new Date(a).toISOString();

console.log(c);

let e = new Date(d).toISOString();

console.log(e);

OutPut:

"2021-01-27T02:02:00.000Z"

"Invalid time value"

Question: What is the difference between how JavaScript interprets variables a and d that it spits out such different outputs?

Share Improve this question edited Mar 3, 2021 at 8:46 samuei 2,1321 gold badge12 silver badges29 bronze badges asked Mar 3, 2021 at 5:41 soumyadeb ghoshalsoumyadeb ghoshal 2911 gold badge5 silver badges11 bronze badges 1
  • Try to use Markdown, so that your code will bee readable. – Miu Commented Mar 3, 2021 at 5:42
Add a ment  | 

3 Answers 3

Reset to default 4

Creating a Date object from a date string parses formats recognized by RFC 2822. While it accepts PST as a valid (although obsolete) timezone for "Pacific Standard Time", it doesn't accept IST as a valid timezone within the timestamp.

Instead, you'd want to replace IST with GMT+0530 or UTC+0530 (meaning Greenwich Mean Time / Coordinated Universal Time + 5h 30min, the definition for India Standard Time):

let c = new Date("26-Jan-2021 06:02 PM GMT+0530").toISOString()
console.log(c) // => '2021-01-26T12:32:00.000Z'

As I understand it, the new Date() constructor for a timestamp string accepts IETF-Compliant RFC 2822 timestamps. Page 31 of the RFC lists the timezones that are acceptable. IST isn't one of them. Therefore, your date string is invalid.

use GMT+0530 instead of IST as IST is not identified as timezone in JS (not recognized by RFC-2822)

let dateSample = new Date("26-Jan-2021 06:02 PM GMT+0530").toISOString()
console.log(dateSample)

prints: 2021-01-26T12:32:00.000Z

发布评论

评论列表(0)

  1. 暂无评论