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

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

javascriptで、エラー「Uncaught TypeError: xxx.format is not a function」が発生した場合の原因と解決方法を記述してます。「moment.js」などを使用せずに「format」を使用した場合に発生します。「chrome」や「firefox」や「safari」の各ブラウザのエラーメッセージの画像もキャプチャしてます。

環境

  • OS windows11 pro 64bit
  • ブラウザ chrome 110.0.5481.78

エラー内容

以下の、「format」で日付のフォーマットを指定しようとしたコードで発生。

const date = new Date();

console.log( date ); // Fri Nov 11 2022 08:51:16 GMT+0900 (日本標準時)

const result = date.format('YYYY-MM-DD');

エラーメッセージ

Uncaught TypeError: date.format is not a function

画像

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

Uncaught TypeError: date.format is not a function

画像

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

TypeError: date.format is not a function. (In 'date.format('YYYY-MM-DD')', 'date.format' is undefined)

画像

原因

「javascript」には日付のフォーマットを指定する「format」という関数はないため

解決方法

日付をフォーマットするのであれば、以下のようにするか、

function format(dt) {

  let y = dt.getFullYear();

  let m = ('00' + (dt.getMonth()+1)).slice(-2);

  let d = ('00' + dt.getDate()).slice(-2);

  return (`${y}-${m}-${d}`);

}

const result = format(new Date());

console.log( result ); // 2022-11-11

「moment.js」を使用して「format」関数します。
※ここではCDN版を使用します。

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

<script>

const date = new Date();

const result = moment(date).format('YYYY-MM-DD');

console.log( result ); // 2022-11-11

</script>