LoginSignup
8
7

More than 3 years have passed since last update.

JavaScript ミリ秒を秒、分、時間、日にちに変換する方法

Posted at

まず、定数nowにDate()オブジェクトをインスタンス化(初期化)したものを代入。
now.getTimeメソッドで求められるのは、1970年1月1日0時0分から現在までの時間をミリ秒(1/1000秒)で表した数字。

const now=new Date();
const time=now.getTime();

まずは、秒を求める。

const sec = Math.floor(time/1000)%60;

もし、now.getTime()で得られた数値が1655555555000(ミリ秒)だとしたら、
定数time/1000で秒数になる。
60(1分=60秒)で割った余りがまだ1分に満たない秒数つまり、秒となる。

次に、分を求める。

const min=Math.floor(time/1000/60)%60;

Math.floor(分数)を60分(1時間)で割った余り。つまり、まだ1時間に満たない分数。

次に、時間を求める。

const hours=Math.floor(time/1000/60/60)%24;

Math.floor(時間)を24時間で割った余り。つまり、まだ24時間(1日)に満たない時間。

const days=Math.floor(time/1000/60/60/24);

Math.floor(日数)。つまり、24時間で割った数。

8
7
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
8
7