日本語

Fixing “Invalid time value” in JavaScript

​​JavaScript​Node.js,Troubleshooting

When you see RangeError: Invalid time value in the browser console or the Node.js terminal, it means you called toISOString() on a Date made from a string that cannot be parsed as a date. It also appears when you pass an invalid Date to Intl.DateTimeFormat. This often happens when you convert a booking date entered in a form, or a date received as a command-line argument, into the format an API expects (2026-11-13T00:00:00.000Z). Calling new Date() does not throw. The error happens at the point where toISOString() is called. If you normalize the string to the form 2026-11-13 and check whether getTime() returns NaN before calling toISOString(), the error goes away.

In my test environment, I caused this error in both a Node.js script and a browser page, and I copied the messages exactly as they appeared. I also confirmed that the error stops appearing after the fix.

Note

The test environment was Ubuntu 24.04 with Node.js 22.23.4, and the time zone was UTC. For the browser, I used Chromium 153 launched with Playwright 1.63.0, and I served the page with Python 3.11's http.server. I retrieved console messages through the DevTools protocol and also captured screenshots of the DevTools panel. I did not test Firefox, Safari, time zones other than UTC, or date libraries.

Calling toISOString() on an unreadable date in Node.js

I prepared a script, to-iso.mjs, that takes a date from a command-line argument, converts it to an ISO-format string, and prints it.

js
const text = process.argv[2];
const date = new Date(text);
console.log(date.toISOString());

Passing 2026-11-13 printed 2026-11-13T00:00:00.000Z. Passing 13/11/2026, which is day/month/year, printed the following in the terminal, and the exit code was 1. The file path is replaced with /path/to/.

text
$ node to-iso.mjs 13/11/2026
file:///path/to/to-iso.mjs:3
console.log(date.toISOString());
                 ^

RangeError: Invalid time value
    at Date.toISOString (<anonymous>)
    at file:///path/to/to-iso.mjs:3:18
    at ModuleJob.run (node:internal/modules/esm/module_job:343:25)
    at async onImport.tracePromise.__proto__ (node:internal/modules/esm/loader:681:26)
    at async asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:117:5)

Node.js v22.23.4

The ^ marker and to-iso.mjs:3:18 point to column 18 on line 3, which is the start of toISOString. The line at Date.toISOString (<anonymous>) above it shows that the error occurred inside toISOString(). Line 2, new Date(text), does not appear as the error location.

Running node to-iso.mjs with no argument produced exactly the same message. process.argv[2] is undefined, and according to the MDN description of the Date() constructor, undefined is treated as the number NaN, so new Date(undefined) becomes an Invalid Date.

new Date() does not throw

The same MDN page for the Date() constructor says that when you pass a string that cannot be read as a date, new Date() does not throw. It returns a Date object that is an "Invalid Date". Its toString() returns "Invalid Date", and its internal numeric value is NaN.

In my test environment, I tried common conversions on a Date created with new Date('2026年11月13日'). The results were the same in Node.js and Chromium.

What I tried Result
String(date) "Invalid Date"
date.getTime() NaN
date.toLocaleDateString('ja-JP') "Invalid Date"
date.toJSON() null
JSON.stringify({ date }) {"date":null}
date.toISOString() RangeError: Invalid time value
new Intl.DateTimeFormat('ja-JP').format(date) RangeError: Invalid time value

Only toISOString() and the format() method of Intl.DateTimeFormat threw an error. The MDN description of toISOString() also states that it throws a RangeError when the date is an Invalid Date.

As the MDN description of toJSON() explains, toJSON() returns null for an Invalid Date instead of throwing. Because JSON.stringify() calls toJSON(), passing a Date directly to JSON.stringify() did not throw, and the date was turned into null.

Warning

Even if you drop toISOString() and let JSON.stringify() handle the conversion, an unreadable date is still sent as null. You need a separate check to detect unreadable dates.

If getTime() is NaN, do not call toISOString()

As the MDN description of getTime() explains, getTime() on an Invalid Date returns NaN. So I added a check with Number.isNaN(date.getTime()) before calling toISOString(). If the date cannot be read, the script prints a message and exits.

js
const text = process.argv[2];
const date = new Date(text);
if (Number.isNaN(date.getTime())) {
  console.error(`日付として読めません: ${text}`);
  process.exit(1);
}
console.log(date.toISOString());

Passing 13/11/2026 printed 日付として読めません: 13/11/2026. Running it with no argument printed 日付として読めません: undefined. The RangeError no longer appeared. Passing 2026-11-13 printed 2026-11-13T00:00:00.000Z, the same as before the fix.

When it happens in a browser form

Next is a page where the user enters a booking date, clicks "Send", and the value to be sent is shown on screen.

html
<label>予約日 <input id="date" type="text"></label>
<button id="save" type="button">送信</button>
<p id="out"></p>
<script type="module" src="main.js"></script>

In main.js, the entered text is passed directly to new Date().

js
const input = document.getElementById('date');
const out = document.getElementById('out');

document.getElementById('save').addEventListener('click', () => {
  const date = new Date(input.value);
  out.textContent = `送る値:${date.toISOString()}`;
});

Entering 2026-11-13 and clicking the button showed 送る値:2026-11-13T00:00:00.000Z ("Value to send: 2026-11-13T00:00:00.000Z") on the page. Entering 2026年11月13日 and clicking the button showed nothing on the page, and the DevTools Console panel displayed the following. (The page's button label is 送信 (Send), and its output label is 送る値 (Value to send).)

text
Uncaught RangeError: Invalid time value
    at Date.toISOString (<anonymous>)
    at HTMLButtonElement.<anonymous> (main.js:6:33)
Screenshot of the DevTools Console panel. A row with a light red background shows "Uncaught RangeError: Invalid time value", and below it are the lines "at Date.toISOString (<anonymous>)" and "at HTMLButtonElement.<anonymous> (main.js:6:33)".
Chromium DevTools after entering `2026年11月13日` and clicking Send

HTMLButtonElement.<anonymous> is the unnamed function registered as the button's click handler. main.js:6:33 is the position of toISOString on line 6. Entering 13/11/2026, and clicking the button without entering anything, produced the same error (RangeError: Invalid time value, at main.js:6:33).

According to the MDN explanation of the "invalid date" error, the wording of this error differs between browsers. RangeError: Invalid time value is the message from V8-based browsers and Node.js. MDN says Firefox shows RangeError: invalid date, and Safari shows RangeError: Invalid Date.

Which strings can be read as dates

According to the MDN description of Date, the only format that every environment is required to parse is a simplified ISO 8601 form such as 2026-11-13 or 2026-11-13T10:00:00. Whether other formats are parsed depends on the browser or runtime.

In my test environment, I passed several values to new Date(). The results were the same in Node.js and Chromium.

Value passed Result
'2026-11-13' 2026-11-13T00:00:00.000Z
'2026/11/13' 2026-11-13T00:00:00.000Z
'2026年11月13日' Invalid Date
'13/11/2026' Invalid Date
'2026-13-01' Invalid Date
'' (empty string) Invalid Date
undefined Invalid Date
'2026-02-30' 2026-03-02T00:00:00.000Z
null 1970-01-01T00:00:00.000Z

'2026/11/13' was parsed, but it is not an ISO format. According to the MDN description, other browsers may not parse it.

The last two rows are examples where no error occurs but the resulting date is wrong. February 30 rolled over to March 2, and null became January 1, 1970. The MDN Date description also notes that the handling of dates such as February 30 varies by runtime. The MDN description of the Date() constructor explains that null is treated as 0.

Normalize the input to ISO format before creating the Date

I changed main.js so that the input is normalized to the form 2026-11-13 before it is passed to new Date(). If the input cannot be read, the page shows a message and does not call toISOString().

js
const input = document.getElementById('date');
const out = document.getElementById('out');

// Normalize the forms with year/month/day separators, slashes, or hyphens to the ISO form and create a Date
function parseDate(text) {
  const m = text.trim().match(/^(\d{4})[年/-](\d{1,2})[月/-](\d{1,2})日?$/);
  if (!m) return null;
  const iso = `${m[1]}-${m[2].padStart(2, '0')}-${m[3].padStart(2, '0')}`;
  const date = new Date(iso);
  // Reject dates that cannot be read, and dates whose day rolled over, such as February 30
  if (Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== iso) return null;
  return date;
}

document.getElementById('save').addEventListener('click', () => {
  const date = parseDate(input.value);
  if (date === null) {
    out.textContent = '日付は「2026年11月13日」の形で入力してください';
    return;
  }
  out.textContent = `送る値:${date.toISOString()}`;
});

On line 11, in addition to checking whether getTime() is NaN, the code also rejects the case where the first 10 characters of toISOString() differ from the normalized string. When February 30 rolls over to March 2, 2026-03-02 does not match 2026-02-30, so the input is rejected here.

I entered each of the following values in the fixed page and clicked "Send". No error appeared in any case. For 2026年11月13日 and 13/11/2026, the DevTools Console panel was also empty.

Input Text shown on the page
2026-11-13 送る値:2026-11-13T00:00:00.000Z (Value to send: 2026-11-13T00:00:00.000Z)
2026年11月13日 送る値:2026-11-13T00:00:00.000Z (Value to send: 2026-11-13T00:00:00.000Z)
2026/11/13 送る値:2026-11-13T00:00:00.000Z (Value to send: 2026-11-13T00:00:00.000Z)
13/11/2026 日付は「2026年11月13日」の形で入力してください (a prompt to enter the date in the form 2026年11月13日)
2026年2月30日 日付は「2026年11月13日」の形で入力してください (a prompt to enter the date in the form 2026年11月13日)
(empty) 日付は「2026年11月13日」の形で入力してください (a prompt to enter the date in the form 2026年11月13日)

According to the MDN Date description, a date-only ISO form such as 2026-11-13 is read as UTC. That is why the output of toISOString() ends with T00:00:00.000Z.

​Posted by 86