🔥

JavaScriptのDateクラスで現在時刻を取得

2023/04/16に公開
  // timestampを取得する関数
  const getTimeStampFromDateClass = () => {
    // 現在の日時を取得
    const currentDate = new Date();

    // オフセットを0時間として設定
    const offsetInHours = 0;

    // オフセットを考慮して新しい日付オブジェクトを生成
    const jstDate = new Date(
      currentDate.getTime() + offsetInHours * 60 * 60 * 1000
    );
    // 年を取得
    const year = jstDate.getFullYear();

    // 月を取得し、2桁に0埋め
    const month = String(jstDate.getMonth() + 1).padStart(2, "0");

    // 日を取得し、2桁に0埋め
    const day = String(jstDate.getDate()).padStart(2, "0");

    // 時を取得し、2桁に0埋め
    const hours = String(jstDate.getHours()).padStart(2, "0");

    // 分を取得し、2桁に0埋め
    const minutes = String(jstDate.getMinutes()).padStart(2, "0");

    // 秒を取得し、2桁に0埋め
    const seconds = String(jstDate.getSeconds()).padStart(2, "0");

    // タイムスタンプ文字列を作成
    const timestampString = `${year}${month}${day}${hours}${minutes}${seconds}`;

    // タイムスタンプ文字列をコンソールに出力
    console.log("↓Dateクラスで取得した現在時刻↓");
    console.log(timestampString);
  };
  getTimeStampFromDateClass();

※基本はdayjsなどのライブラリを使う方が良い

Discussion