こんにちは!今回はPHPのdate関数について、実践的な例を交えながら詳しく解説します。
目次
- date関数とは
- 基本的な使い方
- フォーマット文字一覧
- 実践的な使用例
- よくあるエラーと対処法
date関数とは?
指定したフォーマットで日付と時刻を取得するPHP関数です。
string date(string $format, ?int $timestamp = null)基本的な使い方
1. 現在の日時を取得
// 基本的な日付フォーマット
echo date('Y-m-d'); // 2024-01-01
echo date('Y/m/d'); // 2024/01/01
echo date('Y年m月d日'); // 2024年01月01日2. よく使うフォーマット文字
// 日付関連
'Y' // 4桁の年(例:2024)
'y' // 2桁の年(例:24)
'm' // 月(01-12)
'n' // 月(1-12)
'd' // 日(01-31)
'j' // 日(1-31)
'w' // 曜日(0-6)
'l' // 曜日の完全な表記
// 時間関連
'H' // 24時間形式(00-23)
'h' // 12時間形式(01-12)
'i' // 分(00-59)
's' // 秒(00-59)
'a' // am/pm
'A' // AM/PM実践的な使用例
1. 日本語の日付フォーマット
function getJapaneseDate($timestamp = null) {
    $weekdays = ['日', '月', '火', '水', '木', '金', '土'];
    $w = date('w', $timestamp);
    return date('Y年n月j日', $timestamp) . 
           "({$weekdays[$w]})";
}
echo getJapaneseDate(); // 2024年1月1日(月)2. タイムスタンプの活用
// 特定の日時のタイムスタンプを作成
$timestamp = mktime(0, 0, 0, 1, 1, 2024);
echo date('Y-m-d', $timestamp);
// 1週間後の日付
echo date('Y-m-d', strtotime('+1 week'));
// 来月の最初の日
echo date('Y-m-d', strtotime('first day of next month'));3. 日付の比較
function isWeekend($date) {
    $w = date('w', strtotime($date));
    return ($w == 0 || $w == 6);
}
function getDaysBetween($date1, $date2) {
    $timestamp1 = strtotime($date1);
    $timestamp2 = strtotime($date2);
    return floor(($timestamp2 - $timestamp1) / (60 * 60 * 24));
}4. カスタムカレンダーの作成
function generateCalendar($year, $month) {
    $firstDay = mktime(0, 0, 0, $month, 1, $year);
    $daysInMonth = date('t', $firstDay);
    $startWeekday = date('w', $firstDay);
    $calendar = [];
    $day = 1;
    for ($i = 0; $i < 6; $i++) {
        $week = [];
        for ($j = 0; $j < 7; $j++) {
            if (($i == 0 && $j < $startWeekday) || 
                ($day > $daysInMonth)) {
                $week[] = '';
            } else {
                $week[] = $day++;
            }
        }
        $calendar[] = $week;
        if ($day > $daysInMonth) break;
    }
    return $calendar;
}5. 年齢計算
function calculateAge($birthdate) {
    $birth = strtotime($birthdate);
    $today = time();
    $age = date('Y', $today) - date('Y', $birth);
    if (date('md', $birth) > date('md', $today)) {
        $age--;
    }
    return $age;
}エラーハンドリング
1. 日付の妥当性チェック
function isValidDate($date) {
    $d = date_parse($date);
    return $d['error_count'] === 0 && 
           checkdate($d['month'], $d['day'], $d['year']);
}2. タイムゾーン設定
// タイムゾーンの設定
date_default_timezone_set('Asia/Tokyo');
function getDateWithTimezone($format = 'Y-m-d H:i:s') {
    return date($format);
}便利なユーティリティ関数
1. 日付範囲の生成
function generateDateRange($start, $end) {
    $dates = [];
    $current = strtotime($start);
    $last = strtotime($end);
    while ($current <= $last) {
        $dates[] = date('Y-m-d', $current);
        $current = strtotime('+1 day', $current);
    }
    return $dates;
}2. 営業日計算
function addBusinessDays($date, $days) {
    $timestamp = strtotime($date);
    $count = 0;
    while ($count < $days) {
        $timestamp = strtotime('+1 day', $timestamp);
        if (!isWeekend(date('Y-m-d', $timestamp))) {
            $count++;
        }
    }
    return date('Y-m-d', $timestamp);
}注意点とベストプラクティス
- タイムゾーンの設定を忘れずに
- 日付の妥当性チェック
- 国際化対応の考慮
- パフォーマンスの最適化
まとめ
date関数は日付処理の基本となる重要な関数です。
以下のポイントを押さえておきましょう:
- 適切なフォーマット指定
- タイムゾーンの考慮
- エラーハンドリング
- 国際化対応
以上でdate関数の解説を終わります!
ご質問があればお気軽にどうぞ!
 
  
  
  
  