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

【JavaScript】月初・月末取得や日数0付けや日付比較

Last updated at Posted at 2020-04-03

概要

JavaScriptのDateオブジェクトを使用している中で、よく忘れてしまう事を備忘録として残します。

月初の取得

 function getFirstDate (date) {
   return new Date(date.getFullYear(), date.getMonth(), 1);
 }
 var date = getFirstDate(new Date());
 console.log(date); // Wed Apr 01 2020 00:00:00 GMT+0900 (日本標準時)

月末の取得

 function getLastDate (date) {
   return new Date(date.getFullYear(), date.getMonth() + 1, 0);
 }
 var date = getLastDate(new Date());
 console.log(date); // Thu Apr 30 2020 00:00:00 GMT+0900 (日本標準時)

日付や月の前に0を付ける

 var today = new Date();
 var date = ("0"+today.getDate()).slice(-2);
 var month = ("0"+ (today.getMonth()+1)).slice(-2); 
 console.log(`${today.getFullYear()}-${month}-${date}`) // 2020-04-04  

日付の比較

 var date1 = new Date();
 var date2 = new Date("2020-03-01");
 console.log(date1.getTime() > date2.getTime()) // true
1
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
1
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?