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】日付の取得、計算、バリデーション (Dateオブジェクト)

Posted at

はじめに

日付の取得、日付の計算、便利なバリデーションなど学んだことを自分用のメモとして残します。
※後にlet,constなどの宣言について学ぶので今回は'var'を使用しています。

Dateオブジェクトについて

DateオブジェクトはJavaScriptにもともと組み込まれているオブジェクトで、日付を取得したり、時間を計算する場合などによく使われます。

簡単に参考例を挙げてみます。

js
// 本日の日時を取得する事ができます。
var today = new Date();

//取得したtoday(本日の日時)の西暦のみを取得します。
var Year = today.getFullYear();
//取得したtoday(本日の日時)の西暦のみを取得します。
var Day = today.getDate();
//取得したtoday(本日の日時)の西暦のみを取得します。
var Time = today.getHours();
.
.
.
//など調べると多くのメソッドがあります。

日付を入力してもらうプログラムを作る時など、日時を任意に設定することもできます。

js
//各場所に数字を入力することで設定する事ができます。
//new Date(年, 月, 日,,,)←時間まで指定する事ができます
var date = new Date(2020, 7, 20);


//変数を当てはめることもできる

var y = 2020;
var m = 7;
var d = 20;

var date = new Date(y, m-1, d);
// 月は「0」を起点(1月 = 0)とするので「-1」で調整します

日付の計算

日付を取得して計算をすることもできます。
年、月、日などの計算もできます。

js
const date1 = new Date(2020, 7, 20);


date.setDate(date.getDate() + 3);
//3日後
//3日前を求めるときは - にします


date.setYear(date.getyear() + 3);
//年の計算
date.setMonth(date.getMonth() + 3);
//月の計算



日付のバリデーション

日付を入力してもらうプログラムなどの際の有効な数字を以下のコードを使用することで簡単にチェックする事ができます。
(※半角英数字、文字数などのバリデーションは必要に応じて設定しないといけません。)

js
var y = 2020;
var m = 7;
var d = 20;

var date = new Date(y, m-1, d);

var month = date.getMonth() + 1;
// 月は「0」を起点とするので今度は「+1」で調整します

if(m == month){
 var result = "有効な日付";
} else {
 var result = "無効な日付";
}

Dateオブジェクトで日付を取得する時、「7」を指定しているのに「Aug(8月)」になってしまいます。それは月は「0」を起点とするので7だと8月になります。(0 = 1月)

ですから、**var date = new Date(y, m-1, d);**で取得する時にm(月に−1しています)。

では、**13月に相当する「12」**を指定するとどうなるかというと、

js
var today = new Date(2020, 12, 1);


console.log(today)

//Fri Jan 01 2021 00:00:00 GMT+0900 (日本標準時)

**月が1つ進んで2021年1月1日(水)**が返ってきます。

これは日の部分も同じで、たとえば4月30日までしかないのに、4月31日を指定すると、以下のように5月1日が返されます。

js
//2020年4月31日を指定
var today = new Date(2020, 3, 31);

//Fri May 01 2020 00:00:00 GMT+0900 (日本標準時)

この特性を使って、指定した月と返ってくる月が同じかどうか調べれば、日付が有効かどうか分かるということなんですね。

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?