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?

More than 3 years have passed since last update.

Javacript Dateメソッド わかりやすく日時を表示する

Last updated at Posted at 2020-05-24

Dateオブジェクト

1現在の日時を取得する
2過去や未来の日時を指定する
3日時の計算をする

①Dateオブジェクトを使う際は初期化をする

const now = new Date();

newはオブジェクトを初期化するためのキーワード。

現在日時を記憶した状態でDateオブジェクトを初期化する
new Date();

②年、月、日などを個別に取得する

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;

*now.getMonth・・・実際の月-1になるため+1しないといけない

12時間時計にしてみよう

① ampmを定義し、空の文字列(文字列が0個の文字列)を代入して準備する

let ampm = '';

②午前中、午後に場合わけ

 let ampm ='';
    if(hour < 12){
        ampm ='a.m.';
    } else{
        ampm = 'p.m.'
    }

③24時間→12時間に変える

 const output = `${year}/${month + 1}/${date} ${hour%12}:${min}${ampm}`;
0
0
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
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?