LoginSignup
2
2

More than 3 years have passed since last update.

[Js]日付と時間の取得方法

Last updated at Posted at 2019-12-27

アウトプットとして記載していきますので間違っていましたらご指摘お願い致します。
では本題に入っていきます。

Dateオブジェクト

Dateオブジェクトとは....?
Dateオブジェクトは組み込み関数と言われていて主に日付や時間を取り扱うことができます。
では初めていきましょう!!!!

現在を取得する書き方


let now = new Date(); //new Dateで現在の時間を出力される
console.log(now);

//出力結果
//Fri Dec 27 2019 11:39:47 GMT+0900 (日本標準時)


と出力される

月を取得する書き方


let now = new Date();
console.log(now);

//出力結果
//Fri Dec 27 2019 11:39:47 GMT+0900 (日本標準時)

let months = now.getMonth();
console.log(months);

//出力結果
//11

お気づきでしょうか??
現在を取得してnew Date();で出力したのがDec(12月)となっているのに出力結果が11となりました。
ここで注意して欲しいのが、now.getMonth();は返り値が0からのカウントになっているため少しズレが生じているのである。つまり、0が1月からカウントされているためそのまま数えていくと12月が11月表示になる。なので、インクリメントが必要になる。書き方としては、、、、、、、、、????
*インクリメントとは、変数の値を1増やす演算のことである。 逆に、1減らす演算はデクリメント (decrement) である。


let months = now.getMonth()+1;
console.log(months);

//出力結果
//12

となる。
now.getMonth()の値にnow.getMonth()+1;とすることで12表記になります。

日にちを取得する書き方

let now = new Date();
console.log(now);

//出力結果
//Fri Dec 27 2019 11:39:47 GMT+0900 (日本標準時)

let date = now.getDate();
console.log(date);

//出力結果
//27

となる。
これの場合は返り値が1から始まっているので、逆にインクリメントは必要ない!!!!!

曜日の取得の書き方

//今
let  now = new Date();

//日にち
let date=now.getDate();

//月
let month =now.getMonth()+1;

//年
let year = now.getFullYear();


let week =["","","","","","",""]
let day =week[now.getDay()];


let present = year + "" + month +""+ date2 + "" + day;
console.log(present);

//出力結果
//2019年12月27日金

となる。

時刻を取得の書き方

let now = new Date();

let hours = now.getHours();

let minutes = now.getMinutes();

let seconds = now.getSeconds();

let time = hours + '' + minutes + '' + seconds + '';

console.log(time);


//出力結果
//13時50分1秒

となる。

ついでに

下記の違いは何が違うのかわかりますでしょうか???

let day-one = new Date();
let day-two = Date.now();


console.log(day-one);
//出力結果
//Fri Dec 27 2019 11:39:47 GMT+0900 (日本標準時)


console.log(day-two);
//出力結果
//1577425009654

となる。
両者の違いとしては、ミリ秒で出力されているかどうかの違いだ。
どれも同じ時間表示されている。
しかし、用途によっては使い分けが必要なので覚えておいて損はないでしょう!!!!!
以上です!!!!

もし、何か間違っていることやまだもっといい書き方やこんなのもあるよがあったら教えていただけると幸いです!!!!

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