1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Next.jsでWordPress REST APIの値をカスタマイズ2

1
Posted at

日付をカスタマイズ

フロントをNext.jsで作成して、WP REST APIでお知らせ記事を引っ張ってくる際に返却される値が扱いづらいのでコネコネ。

加工前

image.png

/wp-json/wp/v2/postsで返却された日付の形式が冗長なのでシンプルな形式に!

関数

export function formatDate(
  dateString: string,
  saparator: string = ".",
): string {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}${saparator}${month}${saparator}${day}`;
}

JavaScriptのDateオブジェクトで年月日をそれぞれ分けて成形
getFullYear()で年
getMonth()では0~11が返ってくるので+1、padStartで一桁の場合は0を付与
日をgetDate()で取得、getDay()は曜日が返却されるので誤認注意
最後にsaparatorでつないでreturn返却

date={formatDate(post.date)}

page.tsxで呼び出し

加工後

image.png

デザイン通りの形式で実装できました!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?