0
1

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 5 years have passed since last update.

JavaScript勉強の記録その19: Dateオブジェクトを使って現在時刻を取得

0
Posted at

Dateオブジェクトを利用して現在時刻を取得

new Date()としてあげると、現在時刻に関するデータを持つオブジェクトを生成することができます。
Dateオブジェクトには標準でいくつかのメソッドが用意されてあり、日時に関するデータを取得することができるようになっています。

index.js
const d = new Date();
console.log(d);
//=>Mon Jan 13 2020 23:59:08 GMT+0900 (日本標準時)

getFullyearメソッド

以下の例では、生成されたDateオブジェクトがもつ西暦の情報を取得しています。

index.js
const d = new Date();
console.log(d.getFullYear());
//=>2020

getMonthメソッド

読んで字の如しですが、月に関する情報を取得します。
たた注意する点としては、JavascriptのgetMonthメソッドで返ってくる値は、0は1月を表し、1は2月を表します。
したがって、返ってくる値に+1としてあげることで、現在の月を表すことができます。

index.js
const d = new Date();
console.log(`${d.getMonth() + 1}月`);
//=>1月

getDateメソッド

日付に関する情報を取得します。

index.js
const d = new Date();
console.log(`${d.getDate()}日`);
//=>14日

getDayメソッド

曜日に関する情報を取得します。
こちらも注意が必要で、日曜日は0 月曜日は1 火曜日は2という感じで返ってきます。

index.js
const d = new Date();
console.log(d.getDay()); 
//=>2

そのほか時間に関するメソッド 

時間に関するメソッドは以下となっています。

index.js
console.log(d.getHours()); //0~23時
console.log(d.getMinutes()); //0~59分
console.log(d.getSeconds()); //0~59秒
console.log(d.getMilliseconds()); //0~999ミリ秒
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?