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?

午前 or 午後◯◯:◯◯ や ◯◯日前と日時を表示する

Last updated at Posted at 2025-08-24

この記事はプログラミング学習者がアプリ開発中に躓いた内容を備忘録として記事におこしたものです。内容に不備などあればご指摘頂けると助かります。

0.前提条件

X(旧Twitter)のクローンサイトの制作過程で投稿機能を実装する中で時間の表示について取り扱ったので内容をご紹介したいと思います。

フロントエンド:React(JavaScript) 19.1.0
バックエンド:Ruby on Rails(Ruby) 7.0.0 APIモード
インフラ:Docker
PC;Mac Book Air M2チップ

1. 実装内容

「午前11:37 2025年8月03日」 のように表示させる

TweetDetailsPages.jsx
import dayjs from "dayjs";
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";

dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.tz.setDefault("Asia/Tokyo");

<TimeTag>
  {/* 時間の表示を午前・午後 何時何分 年・月・日で表示 */}
  {dayjs(tweet.created_at)
  .tz("Asia/Tokyo")
  .format("a hh:mm YYYY年MM月DD日")}
</TimeTag>

dayjs.extend(utc): 時間をUTCとして扱うため
dayjs.extend(timezone): .tzと.tz.setDefaultを使えるようにする
dayjs.tz.setDefault("Asia/Tokyo"): デフォルトで使いたいタイムゾーンを指定

dayjs(tweet.created_at).tz("Asia/Tokyo").format("a hh:mm YYYY年MM月DD日)
の場合、tweet.created_atが表示する時間のデータにあたり、
東京時間で 「午前or午後 時:分 年月日」のフォーマットで表示することを表します。
a: 午前or午後
hh: ◯◯時
mm: ◯◯分
YYYY: 西暦で四桁年
MM: ◯◯月
DD: ◯◯日

「21日前」 のように表示させる

RecommendationComponent.jsx
import relativeTime from "dayjs/plugin/relativeTime";
import dayjs, { locale, extend } from "dayjs";
import "dayjs/locale/ja";

// 投稿日の表示を現在の日付から「何日前」で表示する
locale("ja");
extend(relativeTime);

<TimeTag>{dayjs(tweet.created_at).fromNow()}</TimeTag>

locale("ja"): 日本語で表示できるようにする
extend(relativeTime): .fromNowメソッドを使えるようにする
dayjs(tweet.create_at).fromNow()の場合、
tweet.created_atが表示する時間のデータにあたり、今からどれくらい前の日時かを表す
現在:2025年8月24日、created_atの日付が2025年8月3日の場合、21日前と表示されます。

以上が日付を表示する際に使用したdayjsの機能紹介となります。

表示内容については本家のX(旧Twitter)に合わせました。

最後まで読んでいただきありがとうございます。

参考にしたサイト

Day.js
Day.js(dayjs)の使い方まとめ
タイムゾーンを意識した Day.js オブジェクトの生成

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?