萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 獲取當前/指定日期星期幾:中英文顯示、時間戳轉換、碰撞修正

核心函數

date('l')   // 英文完整 星期名 (Sunday)
date('D')   // 英文縮寫 (Sun)
date('w')   // 數字 0(日)-6(六)
date('N')   // ISO-8601 1(一)-7(日) **推薦**

中文星期顯示

$week = ['日', '一', '二', '三', '四', '五', '六'];
echo '星期' . $week[date('w')];          // 今日
echo '星期' . $week[date('w', $timestamp)]; // 指定時間戳
echo '星期' . $week[date('w', strtotime('2024-12-25'))]; // 指定日期字符串

完整工具函數

/**
 * 獲取星期幾
 * @param string|int|null $date 時間戳、日期字符串、null(當前)
 * @param string $lang 'zh'|'en'|'en_short'
 * @return string
 */
function getWeekday($date = null, string $lang = 'zh'): string {
    $timestamp = is_numeric($date) ? (int)$date : ($date ? strtotime($date) : time());
    if ($timestamp === false) throw new InvalidArgumentException('Invalid date');

    $weekZh = ['日', '一', '二', '三', '四', '五', '六'];
    $weekEn = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    $weekEnShort = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

    $index = (int)date('w', $timestamp); // 0-6
    return match ($lang) {
        'zh' => '星期' . $weekZh[$index],
        'en' => $weekEn[$index],
        'en_short' => $weekEnShort[$index],
        default => throw new ValueError("Unsupported lang: $lang"),
    };
}

// 使用
echo getWeekday();                    // 星期一
echo getWeekday('2024-12-25');        // 星期三
echo getWeekday(strtotime('+1 week'), 'en'); // Monday

碰撞修正:strtotime 解析歧義

// 危險:'05/06/2024' 美式 5月6日 / 英式 6月5日
// 安全:ISO 8601 '2024-05-06' 或 明確格式
$ts = strtotime('2024-05-06'); // 明確
$ts = DateTime::createFromFormat('d/m/Y', '06/05/2024')->getTimestamp(); // 明確格式

DateTime 物件導向用法 (PHP 5.2+)

$dt = new DateTime('2024-05-20', new DateZone('Asia/Shanghai'));
echo $dt->format('l');      // Monday
echo $dt->format('w');      // 1
echo $dt->format('N');      // 1 (ISO)
$dt->modify('+1 week');
echo $dt->format('l');      // Monday

批量生成日曆表

function monthCalendar(int $year, int $month): array {
    $firstDay = new DateTime("$year-$month-01");
    $daysInMonth = (int)$firstDay->format('t');
    $startWeekday = (int)$firstDay->format('N'); // 1-7
    $calendar = [];
    $day = 1;
    for ($week = 0; $week < 6; $week++) {
        $calendar[$week] = [];
        for ($wd = 1; $wd <= 7; $wd++) {
            if ($week === 0 && $wd < $startWeekday) {
                $calendar[$week][] = null; // 上月日期
            } elseif ($day <= $daysInMonth) {
                $calendar[$week][] = $day++;
            } else {
                $calendar[$week][] = null; // 下月日期
            }
        }
        if ($day > $daysInMonth) break;
    }
    return $calendar;
}

結語

掌握 date('w')/date('N')、DateTime 物件、strtotime 歧義避坑,**中文顯示只需一個數組映射**。工具函數封裝後全項目複用,避免重複造輪子。

copyright © 萬盛學電腦網 all rights reserved