はじめに
DateTimeクラスに関して整理する。
DateTimeクラスとは
日付/時刻の演算や整形を行うためのクラス。
現在の日付/時刻から生成
php.datetime_now.php
$now = new DateTime();
print $now->format('Y年m月d日 H:i:s'); // 2024年4月14日 12:00:00
日付/時刻文字列から生成
php.datetime_strtotime.php
$now = new DateTime('2024/04/14 12:00:00');
print $now->format('Y年m月d日 H時i分'); // 2024年4月14日 12時00分
タイムゾーンを指定する
datetime_tz.php
$dt1 = new DateTime(null, new DateTimeZone('Asia/Ulan_Bator'));
print $dt1->format('Y年m月d日 H時i分'); //2024年04月14日 10時21分
$dt2 = new DateTime(null, new DateTimeZone('America/Virgin'));
print $dt2->format('Y年m月d日 H時i分'); //2024年04月13日 22時21分
$dt3 = new DateTime(null, new DateTimeZone('Europe/London'));
print $dt3->format('Y年m月d日 H時i分'); //2024年04月14日 03時21分
年月日、時分秒を個別に設定する
datetime_set.php
$now = new DateTime();
$now->setDate(2024, 4, 14);
$now->setTime(11, 24, 30);
print $now->format('Y年m月d日 H:i:s'); //2024年04月14日 11:24:30
タイムスタンプ値を設定する
datetime_ts.php
$now = new DateTime();
$now->setTimestamp(time());
print $now->format('Y年m月d日 H:i:s'); //2024年04月14日 02:30:56
日付/時刻値を指定のフォーマットで整形する
Datetime_format.php
$now = new DateTime();
print $now->format('Y年m月d日 (D) g:i:s a'); // 2024年04月14日 (Sun) 2:35:27 am
print $now->format('当月の日数は t 日です。'); // 当月の日数は 30 日です。
print $now->format('L') ? '閏年です。' : '閏年ではありません。'; // 閏年です。
print $now->format(DateTime::RSS); // Sun, 14 Apr 2024 02:35:27 +0000
日付/時刻文字列を解析する
datetime_fromformat.php
$fmt = 'Y年m月d日 H時i分s秒';
$time = '2024年04月14日 11時39分50秒';
$dt = DateTime::createFromFormat($fmt, $time);
print $dt->format('Y-m-d H:i:s'); // 2024-04-14 11:39:50
日付/時刻文字値を加算/減算する
datetime_add_sub.php
$dt = new DateTime('2024/4/14 11:42:30');
print $dt->format('Y年m月d日 H時i分'); // 2024年04月14日 11時42分
$dt->add(new DateInterval('P1YT10H'));
print $dt->format('Y年m月d日 H時i分'); // 2025年04月14日 21時42分
$dt->sub(new DateInterval('P3MT20M'));
print $dt->format('Y年m月d日 H時i分'); // 2025年01月14日 21時22分
日付/時刻値の差分を取得する
datetime_diff.php
$dt1 = new DateTime('2024/4/14 11:42:30');
$dt2 = new DateTime('2024/12/04');
$interval = $dt1->diff($dt2, true);
print $interval->format('%Y年%m月%d日 %H時%i分%s秒'); // 00年7月19日 12時17分30秒