Next.jsで2023年5月5日(金)のように表示させたかったので、その時の実装メモ。
フォーマットした日付をNext.jsで実装する
結論、以下のようにコードを書くと、2023年5月5日(金)のように表示できる
# libs/formatDate.ts
export const formatDate = () => {
const now = new Date();
const year = now.getFullYear();
const month = now.getMonth() + 1;
const date = now.getDate();
const day = now.getDay();
const week = ["日", "月", "火", "水", "木", "金", "土"][day];
return `${month}月${date}日 (${week})`;
};
const now = new Date();
now
という名前の定数を新しいDateオブジェクトとして宣言する。
DateオブジェクトはJavaScriptで日付と時刻を扱うためのオブジェクトで、引数を指定せずに新しいDateオブジェクトを作成すると、そのオブジェクトは現在の日付と時刻を表す。
const year = now.getFullYear()
DateオブジェクトのgetFullYear()
メソッドを利用して現在の年を取得する。
const month = now.getMonth() + 1;
now.getMonth()
の結果に1を加える。
DateオブジェクトのgetMonth()
メソッドは0から11までの数値を返すため、1を加えて実際の月(1から12)を取得する。
const date = now.getDate();
now.getDate()
で現在の日付を取得できる。
const day = now.getDay();
now.getDay()
は、現在の曜日を0から6の数字で表したものが返ってくる。
具体的には日曜日が0で、土曜日が6となる。
const week = ["日", "月", "火", "水", "木", "金", "土"][day];
配列
["日", "月", "火", "水", "木", "金", "土"]
のday
番目の要素を取得する。
つまり0だったら日を取れるし、1だったら月を取れる
return ${month}月${date}日 (${week});
テンプレートリテラルを使ってフォーマットされた日付を表す文字列を返す。
つまり『2023年5月5日(金)』という形式で返ってくる。
最後に作った関数を以下のようにimportして呼び出せば、任意のページでフォーマットした日付を表示できる。
# index.ts import { formatDate } from "/libs/formatDate"; function TopPage() { const Date = formatDate(); return ( <>{Date}</> ) }