You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP根据纽约时区时段为WordPress元素添加对应CSS类

纯PHP实现纽约时区时段CSS类切换方案

直接替换你代码里的无效判断部分,用24小时制小时数做区间判断更简洁准确,以下是完整可运行的代码:

<?php
$tod_class = '';
date_default_timezone_set("America/New_York");
// 获取当前24小时制小时数(0-23)
$current_hour = (int)date('H');

// 根据时段匹配对应CSS类
if ($current_hour >= 0 && $current_hour < 5) {
    $tod_class = 'tod__twilight';
} elseif ($current_hour >= 5 && $current_hour < 8) {
    $tod_class = 'tod__sunrise';
} elseif ($current_hour >= 8 && $current_hour < 12) {
    $tod_class = 'tod__morning';
} elseif ($current_hour >= 12 && $current_hour < 17) {
    $tod_class = 'tod__afternoon';
} elseif ($current_hour >= 17 && $current_hour < 20) {
    $tod_class = 'tod_sunset';
} else { // 20-23点,对应8pm-12am
    $tod_class = 'tod__night';
}
?>

<div class="bg__color w-100vw h-100vh--40 absolute top-0 left-0 z-1 <?php echo $tod_class; ?>"></div>

关键说明:

  • 用date('H')获取24小时制小时数并转成整数,避免处理时分秒的复杂逻辑,判断更直接
  • 每个条件严格对应需求时段:
    • 0:00-5:00(12am-5am)→ tod__twilight
    • 5:00-8:00(5am-8am)→ tod__sunrise
    • 8:00-12:00(8am-12pm)→ tod__morning
    • 12:00-17:00(12pm-5pm)→ tod__afternoon
    • 17:00-20:00(5pm-8pm)→ tod_sunset
    • 20:00-24:00(8pm-12am)→ tod__night
  • 设置的America/New_York时区会自动处理夏令时(EDT),无需手动调整

内容的提问来源于stack exchange,提问作者TIBrent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 14:02:33