はじめに
Webアプリケーションでは、日付や時間を扱う場面が多くあります。今回は、JavaScriptでDate オブジェクトを使って日付や時刻を取得・操作・表示する方法について記載していきます。
Dateオブジェクトとは
Date オブジェクトは、日時に関する情報(年、月、日、時、分、秒、ミリ秒)を操作できるJavaScriptの標準オブジェクトです。
定義
let now = new Date();
日付や時間の取得
現在の日時を取得
let now = new Date();
console.log(now); // 現在の日時が表示される
現在の日時をそれぞれ単体で取得
Dateオブジェクトには、各種情報を取得するためのメソッドが用意されています。
| メソッド名 | 詳細 | 
| getFullYear() | 年を取得 | 
| getMonth() | 月を取得 | 
| getDate() | 日を取得 | 
| getDay() | 曜日を取得 | 
| getHours() | 時を取得 | 
| getMinutes() | 分を取得 | 
| getSeconds() | 秒を取得 | 
| getMilliseconds() | ミリ秒を取得 | 
例
let now = new Date();
console.log(now.getFullYear()); // 年(例: 2025)
console.log(now.getMonth());    // 月(0〜11。1月は0)
console.log(now.getDate());     // 日(1〜31)
console.log(now.getDay());      // 曜日(0:日曜〜6:土曜)
console.log(now.getHours());    // 時(0〜23)
console.log(now.getMinutes());  // 分(0〜59)
console.log(now.getSeconds());  // 秒(0〜59)
console.log(now.getMilliseconds()); // ミリ秒(0〜999)
特定の日付を指定する
Date コンストラクタにパラメータを渡すことで、任意の日付・時刻を作成できます。
※ 月は0から始まるため、1月は「0」、12月は「11」です。
※ 曜日は0から始まるため、日曜日が「0」、土曜日が「6」です
let birthday = new Date(1997, 0, 15); // 1997年1月15日
console.log(birthday);
日付や時間の加算・減算
日付を操作するには、一度 getDate() などで値を取得し、setDate() で変更します。
例
let today = new Date(); // 今日の日付
console.log("今日:", today);
let sevenDaysLater = new Date(today); // コピーして変更
sevenDaysLater.setDate(today.getDate() + 7); // 7日後
console.log("7日後:", sevenDaysLater);
let threeDaysBefore = new Date(today);
threeDaysBefore.setDate(today.getDate() - 3); // 3日前
console.log("3日前:", threeDaysBefore);
日付・時間のフォーマット
Intl.DateTimeFormat は、日付や時間をローカルの文化や言語に合わせて表示するための国際化対応APIです。手動でフォーマット文字列を組み立てる代わりに、言語コードとオプションを指定するだけで、適切なフォーマットが自動で適用されます。
let date = new Date();
let formatter = new Intl.DateTimeFormat('ja-JP', {
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  weekday: 'long'
});
console.log(formatter.format(date)); // 例: 2025年5月18日 日曜日
最後に
JavaScriptの環境構築は、この記事を参照してみてください。
【JavaScript】VSCodeでJavaScriptを使用するための環境構築を実施する – SEもりのLog JavaScript
以上、ログになります。
これからも継続していきましょう!!

 
  
  
  
  
コメント