javascript エラー「Uncaught TypeError: xxx.toISOString is not a function」の解決方法

javascript エラー「Uncaught TypeError: xxx.toISOString is not a function」の解決方法

javascriptで、エラー「Uncaught TypeError: xxx.toISOString is not a function」が発生した場合の原因と解決方法を記述してます。「Date.now()」のような有効な日付オブジェクト以外に「toISOString」を使用した際に発生します。「chrome」や「firefox」や「safari」の各ブラウザのエラーメッセージの画像もキャプチャしてます。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 111.0.5563.111

エラー内容

以下の、「Date.now()」からISO形式の文字列を取得しようとしたコードにて発生。

const d = Date.now();

console.log(d); // 1668220729072

const result = d.toISOString();

エラーメッセージ

Uncaught TypeError: d.toISOString is not a function

画像

firefox106の場合でも同じエラーが発生します。

Uncaught TypeError: d.toISOString is not a function

画像

safari15.5では、以下のエラーとなります。

TypeError: d.toISOString is not a function. (In 'd.toISOString()', 'd.toISOString' is undefined)

画像

原因

「Date.now()」は、有効な日付オブジェクトではないため

const d = Date.now();
console.log(d); // 1668220729072

解決方法

有効な日付オブジェクトである「new Date()」を使用する

const d = new Date();

console.log(d); // Sat Nov 12 2022 11:44:58 GMT+0900 (日本標準時)

const result = d.toISOString();

console.log(result);
// 2022-11-12T02:45:30.086Z

または、「new Date()」であるかを判定して使用します。

const d = Date.now();

const result = toString.call(d).slice(8, -1) === 'Date' ? d.toISOString() : '有効な日付オブジェクトではありません';

console.log( result ); 
// 有効な日付オブジェクトではありません