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

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

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

環境

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

エラー内容

以下の、日付を文字列に変換するコードで発生。

const d = Date.now();

console.log(d); // 1668471481372

const result = d.toDateString();

エラーメッセージ

Uncaught TypeError: d.toDateString is not a function

画像

firefox106の場合では、以下のエラーが発生します。

Uncaught TypeError: d.toDateString is not a function

画像

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

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

画像

原因

有効な日付オブジェクトではない値を指定しているため。

const d = new Date();

console.log(d); // Tue Nov 15 2022 10:52:32 GMT+0900 (日本標準時)

const result = d.toDateString();

console.log(result); // Tue Nov 15 2022

解決方法

「有効な日付オブジェクト」に「new Date」で変換して使用するか、

const d = Date.now();

console.log(d); // 1668039940763

// 変換
const result = new Date(d).toDateString();

console.log(result); // Tue Nov 15 2022

「有効な日付オブジェクト」であるかを判定してから使用する。

const d = Date.now();

if (typeof d === 'object' && 'toDateString' in d && d !== null) {
  const result = d.toDateString();
  console.log(result);
}else{
  console.log('有効な日付ではありません');
}