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

基于IP获取时区实现对应国家新年倒计时及跳转功能

问题解决代码示例

PHP 部分:基于用户时区判断并跳转

原代码未使用获取到的用户时区,直接依赖服务器本地时间判断,修改后如下:

<?php
// 获取用户IP
$ip = $_SERVER['REMOTE_ADDR'];
// 请求ip-api接口获取时区信息
$ipInfo = file_get_contents('http://ip-api.com/json/' . $ip);
$ipInfo = json_decode($ipInfo);

// 处理API请求失败的容错逻辑
if (!$ipInfo || empty($ipInfo->timezone)) {
    $timezone = 'UTC'; // 设默认时区,可根据需求调整
} else {
    $timezone = $ipInfo->timezone;
}

// 创建用户时区的DateTime实例
$userDateTime = new DateTime('now', new DateTimeZone($timezone));
$userDate = $userDateTime->format('Y-m-d');

// 判断是否为2023年1月1日,是则跳转
if ($userDate === '2023-01-01') {
    header('Location: https://2023.blogsaffair.com/');
    exit; // 跳转后终止脚本,避免后续代码执行
}

// 另一个日期判断示例
if ($userDate === '2023-11-01') {
    header('Location: https://blogsaffair.com');
    exit;
}
?>

关键修正点:

  • 新增API请求失败的容错处理,防止脚本异常
  • 使用DateTime类指定用户时区,确保判断的是用户所在时区的日期
  • 跳转后调用exit,避免无效代码执行

JavaScript 部分:基于用户时区的倒计时

原代码依赖客户端本地时间,修改后通过PHP传递时区,实现用户时区下的精准倒计时:

首先在HTML页面中通过PHP传递时区变量:

<script>
// 将PHP获取的时区传递给JS
const userTimezone = '<?php echo $timezone; ?>';
</script>

然后修改JS倒计时代码:

const secondsText = document.getElementById('seconds');
const minutesText = document.getElementById('minutes');
const hoursText = document.getElementById('hours');
const daysText = document.getElementById('days');
let countdownInterval;

function countDown() {
    // 构造用户时区下的2023年1月1日0点时间对象
    const deadline = new Date(`2023-01-01T00:00:00 ${userTimezone}`);
    // 获取用户时区下的当前时间戳
    const now = new Date(new Date().toLocaleString('en-US', { timeZone: userTimezone })).getTime();
    
    let timeLeft = deadline.getTime() - now;

    // 倒计时结束时停止定时器
    if (timeLeft < 0) {
        clearInterval(countdownInterval);
        // 可在此添加倒计时结束后的逻辑(如页面跳转)
        return;
    }

    // 计算各时间单位数值
    const daysValue = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
    const hoursValue = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutesValue = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
    const secondsValue = Math.floor((timeLeft % (1000 * 60)) / 1000);

    // 更新DOM,补零保证显示格式统一
    secondsText.textContent = secondsValue.toString().padStart(2, '0');
    minutesText.textContent = minutesValue.toString().padStart(2, '0');
    hoursText.textContent = hoursValue.toString().padStart(2, '0');
    daysText.textContent = daysValue.toString().padStart(2, '0');
}

// 初始化倒计时并启动定时器
countDown();
countdownInterval = setInterval(countDown, 1000);

关键修正点:

  • 通过PHP传递用户时区,确保倒计时基于用户所在时区计算
  • 使用toLocaleString指定时区获取当前时间,规避客户端本地时区干扰
  • 添加补零逻辑,优化倒计时显示格式
  • 保存定时器ID,确保能正确停止倒计时

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 19:05:24