Gatsbyのブログで日本時間の日付表示をする

  • 2022年2月25日
  • 2022年2月25日
  • Gatsby
  • 140view

Gatsby のテンプレートの gatsby-starter-blog では初期状態で英語での日付表示になっている。
これを日本語での日付表記に変更する方法をまとめた。

before

Image from Gyazo


after

Image from Gyazo


具体的なコードは該当の PullRequest で確認出来る。

https://github.com/gunners6518/terrblog/pull/36

該当箇所の確認

gatsby-starter-blogでは 記事一覧ページ(index.js)、個別記事ページ(blog-post.js)にて日付けが使われている。

GraphQL では以下の様に fromtmatter でデータを取っている。

frontmatter {
  title
  date(formatString: "MMMM DD, YYYY")
  description
}

dateの部分を整形して英語表記にしているので削る。

表示箇所に組み込み

dateのままだと 2022 年 2 月 23 日の場合は20220223で取得される。
これを 2022 年 2 月 23 日表記にする為ぬにmoments.jsを使って整形する。

{
  moment(post.frontmatter.date).format(`YYYY年MM月DD日`)
}

完成

Image from Gyazo


Select the fields to be shown. Others will be hidden. Drag and drop to rearrange the order.
  • Image
  • SKU
  • Rating
  • Price
  • Stock
  • Availability
  • Add to cart
  • Description
  • Content
  • Weight
  • Dimensions
  • Additional information
  • Attributes
  • Custom attributes
  • Custom fields
Click outside to hide the compare bar
Compare
Compare ×
Let's Compare! Continue shopping