日付とタイムスタンプの相互変換
PHPでは、特定の期間(当日、今週、今月など)の開始時刻と終了時刻をプログラムで取得する必要がある場面が多くあります。以下は、よく使用されるパターンの実装例です。
現在時刻の取得
date_default_timezone_set('Asia/Tokyo'); // タイムゾーン設定(日本基準)
// 現在のタイムスタンプ
$currentTimestamp = time();
echo date('Y-m-d H:i:s', $currentTimestamp); // 出力例: 2025-04-05 14:30:22
本日の開始と終了時刻
// 今日の00:00:00
$startToday = strtotime('today 00:00:00');
// 今日の23:59:59
$endToday = strtotime('today 23:59:59');
昨日の日付範囲
$startYesterday = strtotime('yesterday 00:00:00');
$endYesterday = strtotime('yesterday 23:59:59');
今週の期間(月曜始まり)
// 今週の月曜日の00:00:00
$startThisWeek = strtotime('this week monday 00:00:00');
// 今週の日曜日の23:59:59
$endThisWeek = strtotime('this week sunday 23:59:59');
先週の期間
// 先週の月曜日
$startLastWeek = strtotime('last week monday 00:00:00');
// 先週の日曜日
$endLastWeek = strtotime('last week sunday 23:59:59');
今月の開始と終了
// 今月の1日 00:00:00
$startThisMonth = strtotime(date('Y-m-01 00:00:00'));
// 今月の最終日 23:59:59
$endThisMonth = strtotime(date('Y-m-t 23:59:59'));
先月の期間
// 先月の1日 00:00:00
$startLastMonth = strtotime('first day of last month 00:00:00');
// 先月の最終日 23:59:59
$endLastMonth = strtotime('last day of last month 23:59:59');
今年の期間
// 今年の1月1日
$startThisYear = strtotime(date('Y-01-01 00:00:00'));
// 今年の12月31日
$endThisYear = strtotime(date('Y-12-31 23:59:59'));
去年の期間
// 去年の1月1日
$startLastYear = strtotime((date('Y') - 1) . '-01-01 00:00:00');
// 去年の12月31日
$endLastYear = strtotime((date('Y') - 1) . '-12-31 23:59:59');
日付情報を分解して取得
echo '今年度: ' . date('Y') . '年';
echo '今月: ' . date('n') . '月'; // 先頭ゼロなし
echo '今月の日数: ' . date('t') . '日'; // 当月の最終日を返す
echo '今日は: ' . date('j') . '日'; // 日付(ゼロ埋めなし)
文字列からタイムスタンプへ変換
$dateString = '2025-03-15 10:30:00';
$timestamp = strtotime($dateString);
if ($timestamp !== false) {
echo "変換成功: " . date('Y-m-d H:i:s', $timestamp);
} else {
echo "無効な日付形式";
}
タイムスタンプを日付にフォーマット
$formatted = date('Y年m月d日 H時i分s秒', time());
echo $formatted; // 出力例: 2025年04月05日 14時30分22秒
主なフォーマット指定子:
Y: 四桁の年 (例: 2025)m: 二桁の月 (01~12)d: 二桁の日 (01~31)H: 24時間制の時 (00~23)i: 分 (00~59)s: 秒 (00~59)t: 当月の日数を取得w: 曜日 (0=日曜, 6=土曜)N: ISO曜日 (1=月曜, 7=日曜)