ハッピーメモメモ

私的備忘録

【JavaScript】日時を表示する

例)

<html>
<body>
    <section>
        <p>最終アクセス日時:<span id="time"></span></p>
    </section>
</body>
</html>

<script>
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth();
    const date = now.getDate();
    const hour = now.getHours();
    const min = now.getMinutes();

    const output = `${year}/${month + 1}/${date} ${hour}:${min}`;
    document.getElementById('time').textContent = output;
</script>

▼出力結果

f:id:n-moeko1966:20211026214204p:plain

 

 

〇Dateオブジェクトは初期化する必要がある

const now = new Date();

 newを使って初期化し、定数nowに代入。

 この定数を利用して日時を取得する。

 

==MEMO==========================

初期化するオブジェクト、しないオブジェクト

・複数のオブジェクトが作れるオブジェクトは初期化する

 →初期化=コピーを作成してメモリに保存する

・複数のオブジェクトを作れないオブジェクトは初期化しない

 例えばMathオブジェクトのプロパティはすべて読み取り専用で、

 書き換えができない。

 コピーが作れないから、初期化の必要性がない。

===============================

 

 

〇Dateオブジェクトのメソッドを使って、年・月・日などを個別に取得する

const year = now.getFullYear();
const month = now.getMonth();
const date = now.getDate();
const hour = now.getHours();
const min = now.getMinutes();

※getMonthメソッドは「実際の月-1」の数字が取得されるので、

 出力の際は1を足す必要がある。

 

 

+α

12時間表記にするなら

<script>
const now = new Date();
const year = now.getFullYear();
const month = now.getMonth();
const date = now.getDate();
const hour = now.getHours();
const min = now.getMinutes();
let ampm = '';
if(hour < 12) {
    ampm = 'a.m.';
} else {
    ampm = 'p.m.';
}

const output = `${year}/${month + 1}/${date} ${hour % 12}:${min}${ampm}`;
document.getElementById('time').textContent = output;
</script>