0
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?

【JavaScript(React)でタイムスタンプを「YYYY年M月D日 H時mm分」に整形する方法】

Last updated at Posted at 2025-06-26

タイムスタンプのままだと、2025-06-25T06:41:30.30643みたいな見づらいので、2025年6月25日 6時41分みたいに直す方法の備忘録です!
現在の投稿を表示するコンポーネントの中身はこうです!

import React from "react";
import DeleteButton from "../../button/HomeButton/DeleteButton";
import MovePickupThreadButton from "../../button/HomeButton/MovePickupThreadButton";
import { useContext } from "react";
import { ThreadsContext } from "../../contexts/ThreadsContext";
import UpdateThreadsButton from "../../button/HomeButton/UpdateThreadsButton";
import { Api } from "../../hooks/Api";

const Thread = ({ thread }) => {
  const { reloadThreads } = useContext(ThreadsContext);

  // ここでデータの削除のAPI実行する関数
  const deletePost = async (id) => {
    if (!id) return; //id がない場合は処理しない
    if (!window.confirm("本当に削除しますか?")) return;

    try {
      await Api(`/threads/delete/${id}`, "PUT");
      // ここでデータを消したら一覧取得を再読み込みをしてる
      reloadThreads();
    } catch (error) {
      console.error("削除失敗:", error);
      alert("削除に失敗しました");
    }
  };

  return (
    <li key={thread.id}>
      {/*情報をとってきて並べるときの書き方。 
    li key={thread.id}でthreadのidを紐づけしてる。ユニーク(他と被らない)の値じゃないとダメ*/}
      <h3>タイトル:{thread.title}</h3>
      <p>内容:{thread.content}</p>
      <p>ユーザー: {thread.user.username}</p>
      {/*userメソッドの中のnameを取るって意味になる。*/}
      <p>投稿日:(thread.postedAt)}</p>
      <DeleteButton id={thread.id} onConfirm={deletePost} />
      <UpdateThreadsButton thread={thread} id={thread.id} />
      <MovePickupThreadButton id={thread.id} thread={thread} />
    </li>
  );
};
export default Thread;

んで時間の部分の表示はこうなってます。

postedAt: "2025-06-25T06:36:46.02925"

これをYYYY年M月D日 H時mm分の型にしていきます!

フォーマットして表示する例

<p>
  投稿日: {
    new Date(thread.postedAt).getFullYear()
  }{
    new Date(thread.postedAt).getMonth() + 1
  }{
    new Date(thread.postedAt).getDate()
  }{
    new Date(thread.postedAt).getHours()
  }{
    String(new Date(thread.postedAt).getMinutes()).padStart(2, "0")
  }</p>

でもこれだとめっちゃながい!!!
時間の部分だけ長すぎるのでReactコンポーネントの外に整形関数を作ってあげました。
んで最終的には下記のようになりました!

import React from "react";
import DeleteButton from "../../button/HomeButton/DeleteButton";
import MovePickupThreadButton from "../../button/HomeButton/MovePickupThreadButton";
import { useContext } from "react";
import { ThreadsContext } from "../../contexts/ThreadsContext";
import UpdateThreadsButton from "../../button/HomeButton/UpdateThreadsButton";
import { Api } from "../../hooks/Api";

const Thread = ({ thread }) => {
  const { reloadThreads } = useContext(ThreadsContext);
  
 //ここで日時の形を整形してる!
  const formatJapaneseDate = (isoString) => {
    const date = new Date(isoString);
    return (
      `${date.getFullYear()}${date.getMonth() + 1}${date.getDate()}日 ` +
      `${date.getHours()}${String(date.getMinutes()).padStart(2, "0")}分`
    );
  };

  // ここでデータの削除のAPI実行する関数
  const deletePost = async (id) => {
    if (!id) return; //id がない場合は処理しない
    if (!window.confirm("本当に削除しますか?")) return;

    try {
      await Api(`/threads/delete/${id}`, "PUT");
      // ここでデータを消したら一覧取得を再読み込みをしてる
      reloadThreads();
    } catch (error) {
      console.error("削除失敗:", error);
      alert("削除に失敗しました");
    }
  };

  return (
    <li key={thread.id}>
      {/*情報をとってきて並べるときの書き方。 
    li key={thread.id}でthreadのidを紐づけしてる。ユニーク(他と被らない)の値じゃないとダメ*/}
      <h3>タイトル:{thread.title}</h3>
      <p>内容:{thread.content}</p>
      <p>ユーザー: {thread.user.username}</p>
      {/*userメソッドの中のnameを取るって意味になる。*/}
      <p>投稿日: {formatJapaneseDate(thread.postedAt)}</p>//ここの関数をおいてる!
      <DeleteButton id={thread.id} onConfirm={deletePost} />
      <UpdateThreadsButton thread={thread} id={thread.id} />
      <MovePickupThreadButton id={thread.id} thread={thread} />
    </li>
  );
};
export default Thread;

そして表示はこうなってます!

投稿日: 2025年6月25日 6時41分

完成!!!

0
0
2

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
0
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?