JavaScriptの日付と時間の関数

JavaScriptで日付と時間を操作することは、Webアプリケーションの開発において非常に重要です。
ユーザーのローカル時間を表示したり、イベントの日時を管理したり、
タイマーを実装するために必要です。
本記事では、JavaScriptの日付と時間の関数について詳しく解説します。

基本的なDateオブジェクト

JavaScriptでは、日付と時間を操作するためにDateオブジェクトが使用されます。
Dateオブジェクトは、JavaScriptのビルトインオブジェクトで、
日付と時間に関連するさまざまなメソッドを提供しています。

Dateオブジェクトの作成

Dateオブジェクトを作成する方法は複数あります。

  • 現在の日付と時間を取得
let now = new Date();
console.log(now); // 現在の日付と時間を表示
  • 特定の日付と時間を指定
let specificDate = new Date(2024, 5, 29, 14, 30, 0); // 2024年6月29日 14:30:00
console.log(specificDate);
  • 文字列から日付を作成
let dateString = new Date("2024-06-29T14:30:00");
console.log(dateString);
  • UNIXタイムスタンプから日付を作成
let timestamp = new Date(1624978200000); // UNIXタイムスタンプ(ミリ秒)
console.log(timestamp);

Dateオブジェクトのメソッド

Dateオブジェクトには、日付と時間を操作するための多くのメソッドがあります。以下では、主要なメソッドを紹介します。

現在の日時を取得するメソッド

  • getFullYear:4桁の年を取得します。
let year = now.getFullYear();
console.log(year); // 2024
  • getMonth:月を取得します(0から11の範囲)。
let month = now.getMonth();
console.log(month); // 5(6月)
  • getDate:月の日を取得します。
let date = now.getDate();
console.log(date); // 29
  • getDay:曜日を取得します(0から6の範囲で、0が日曜日)。
let day = now.getDay();
console.log(day); // 6(土曜日)
  • getHours:時間を取得します(0から23の範囲)。
let hours = now.getHours();
console.log(hours); // 14
  • getMinutes:分を取得します。
let minutes = now.getMinutes();
console.log(minutes); // 30
  • getSeconds:秒を取得します。
let seconds = now.getSeconds();
console.log(seconds); // 0
  • getMilliseconds:ミリ秒を取得します。
let time = now.getTime();
console.log(time); // 1624978200123
  • getTime:1970年1月1日からのミリ秒を取得します。
let time = now.getTime();
console.log(time); // 1624978200123

日時を設定するメソッド

  • setFullYear:年を設定します。
now.setFullYear(2025);
console.log(now.getFullYear()); // 2025
  • setMonth:月を設定します。
now.setMonth(11); // 12月
console.log(now.getMonth()); // 11
  • setDate:月の日を設定します。
now.setDate(25);
console.log(now.getDate()); // 25
  • setHours:時間を設定します。
now.setHours(16);
console.log(now.getHours()); // 16
  • setMinutes:分を設定します。
now.setMinutes(45);
console.log(now.getMinutes()); // 45
  • setSeconds:秒を設定します。
now.setSeconds(30);
console.log(now.getSeconds()); // 30
  • setMilliseconds:ミリ秒を設定します。
now.setMilliseconds(500);
console.log(now.getMilliseconds()); // 500
  • setTime:1970年1月1日からのミリ秒を設定します。
now.setTime(1624978200000);
console.log(now.getTime()); // 1624978200000

日付の操作

JavaScriptでは、日付を操作するためのさまざまな方法があります。

日付の加算と減算

日付に日数を加算または減算するには、setDateメソッドを使用します。

let today = new Date();
today.setDate(today.getDate() + 7); // 7日後
console.log(today);

today.setDate(today.getDate() - 14); // 14日前
console.log(today);

月の加算と減算

月を加算または減算するには、setMonthメソッドを使用します。

let currentMonth = new Date();
currentMonth.setMonth(currentMonth.getMonth() + 1); // 1ヶ月後
console.log(currentMonth);

currentMonth.setMonth(currentMonth.getMonth() - 2); // 2ヶ月前
console.log(currentMonth);

年の加算と減算

年を加算または減算するには、setFullYearメソッドを使用します。

let currentYear = new Date();
currentYear.setFullYear(currentYear.getFullYear() + 1); // 1年後
console.log(currentYear);

currentYear.setFullYear(currentYear.getFullYear() - 5); // 5年前
console.log(currentYear);

日付のフォーマット

JavaScriptで日付を特定の形式で表示するには、文字列操作やライブラリを使用します。

基本的な日付のフォーマット

let date = new Date();
let formattedDate = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
console.log(formattedDate); // 2024-6-29

ライブラリを使用したフォーマット

JavaScriptでは、日付と時間のフォーマットを簡単に行うためのライブラリが多数存在します。代表的なものにmoment.jsdate-fnsがあります。

Moment.jsを使用したフォーマット

// Moment.jsをインストールする
// npm install moment

const moment = require('moment');
let now = moment();
console.log(now.format('YYYY-MM-DD HH:mm:ss')); // 2024-06-29 14:30:00

Date-fnsを使用したフォーマット

// Date-fnsをインストールする
// npm install date-fns

const { format } = require('date-fns');
let now = new Date();
console.log(format(now, 'yyyy-MM-dd HH:mm:ss')); // 2024-06-29 14:30:00

タイマーとインターバル

JavaScriptでは、特定の時間後にコードを実行したり、
一定間隔でコードを実行するための関数が提供されています。

setTimeout

setTimeoutは、指定した時間(ミリ秒)後に一度だけ関数を実行します。

setTimeout(() => {
console.log("This message is displayed after 2 seconds.");
}, 2000);

setInterval

setIntervalは、指定した時間(ミリ秒)ごとに関数を繰り返し実行します。

let count = 0;
let intervalId = setInterval(() => {
count++;
console.log(`This message is displayed every 1 second. Count: ${count}`);
if (count === 5) {
clearInterval(intervalId);
}
}, 1000);

clearTimeoutとclearInterval

setTimeoutsetIntervalで設定したタイマーやインターバルをクリアするには、clearTimeoutclearIntervalを使用します。

let timeoutId = setTimeout(() => {
console.log("This message will not be displayed.");
}, 5000);

clearTimeout(timeoutId);

let intervalId = setInterval(() => {
console.log("This message will be displayed every 1 second.");
}, 1000);

clearInterval(intervalId);

タイムゾーンの処理

JavaScriptのDateオブジェクトは、デフォルトでローカルタイムゾーンを使用しますが、
UTCタイムゾーンを使用することもできます。

UTCメソッド

Dateオブジェクトには、UTCを基準とするメソッドがいくつかあります。

  • getUTCFullYear:UTCの4桁の年を取得します。
let utcYear = now.getUTCFullYear();
console.log(utcYear); // 2024
  • getUTCMonth:UTCの月を取得します。
let utcMonth = now.getUTCMonth();
console.log(utcMonth); // 5(6月)
  • getUTCDate:UTCの月の日を取得します。
let utcDate = now.getUTCDate();
console.log(utcDate); // 29
  • getUTCHours:UTCの時間を取得します。
let utcHours = now.getUTCHours();
console.log(utcHours); // 5(現地時間が14:00の場合)

ローカル時間とUTC時間の変換

JavaScriptでローカル時間とUTC時間を相互に変換する方法を見てみましょう。

  • ローカル時間からUTC時間への変換
let localDate = new Date();
let utcDate = new Date(localDate.getTime() + localDate.getTimezoneOffset() * 60000);
console.log(utcDate);
  • UTC時間からローカル時間への変換
let utcDate = new Date(Date.UTC(2024, 5, 29, 14, 30, 0));
let localDate = new Date(utcDate.getTime() - utcDate.getTimezoneOffset() * 60000);
console.log(localDate);

カスタム日付と時間の操作

JavaScriptで日付や時間をより高度に操作するためのカスタム関数を作成することもできます。

指定した日数を加算する関数

function addDays(date, days) {
let result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}

let date = new Date();
console.log(addDays(date, 10)); // 10日後の日付

指定した月数を加算する関数

function addMonths(date, months) {
let result = new Date(date);
result.setMonth(result.getMonth() + months);
return result;
}

let date = new Date();
console.log(addMonths(date, 3)); // 3ヶ月後の日付

指定した年数を加算する関数

function addYears(date, years) {
let result = new Date(date);
result.setFullYear(result.getFullYear() + years);
return result;
}

let date = new Date();
console.log(addYears(date, 5)); // 5年後の日付

日付の差を計算する関数

function dateDifference(date1, date2) {
let differenceInTime = date2.getTime() - date1.getTime();
let differenceInDays = differenceInTime / (1000 * 3600 * 24);
return differenceInDays;
}

let date1 = new Date("2024-06-29");
let date2 = new Date("2025-06-29");
console.log(dateDifference(date1, date2)); // 365日

日付と時間の表示

日付と時間をユーザーに表示する際には、適切なフォーマットで表示することが重要です。

日付を日本語で表示

let date = new Date();
let options = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' };
console.log(date.toLocaleDateString('ja-JP', options)); // 例: 2024年6月29日土曜日

時間を日本語で表示

let timeOptions = { hour: '2-digit', minute: '2-digit', second: '2-digit' };
console.log(date.toLocaleTimeString('ja-JP', timeOptions)); // 例: 14:30:00

まとめ

JavaScriptの日付と時間の関数を理解し、適切に使用することで、
ウェブアプリケーションでの時間管理や表示が効果的に行えます。
基本的なDateオブジェクトの使い方から、非同期処理やタイムゾーンの扱いまで、
さまざまな技術を駆使して、ユーザーにとって使いやすいアプリケーションを作成しましょう。
この記事を参考に、日付と時間の操作をマスターしてみてください。