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で1時間前のdateを作成

Posted at

概要

JavaScriptで1時間前のdateを作成します。

コード

コードは簡潔で下記のように出力できます。

const now = new Date();
const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);

console.log(oneHourAgo) // 1時間前が出力される

コード解説

getTimeは何を返却するのか。

interface Date {
    /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */
    getTime(): number;

getTimeが定義されているinterfaceではミリ秒単位でnumber型を返却するとあります。
そのため、1時間をミリ秒単位にしてミリ秒単位の現在時刻から引くと意図した値を取得できます。

60 * 60 * 1000

  • 1秒は1000ミリ秒
  • 1分は60秒
  • 1時間は60分

よって、上記のコードで1時間前を取得することができます。

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?