服务器修改时区方法

K.exe

2025年09月19日
0

1. 服务器层面(最重要)

检查服务器时间

# 登录服务器 SSH,查看当前服务器时间
date

# 查看服务器时区
timedatectl
# 或
cat /etc/timezone

 

 

设置服务器时区为 Asia/Shanghai(北京时间)

# Ubuntu/Debian
sudo timedatectl set-timezone Asia/Shanghai

# CentOS/RHEL
sudo ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

# 验证
date

 

 

2. WordPress 后台设置

在 WordPress 后台设置正确时区

  1. 进入 设置 → 常规

  2. 时区 选项选择:UTC+8 北京时间 或 上海

  3. 保存更改

 

 

3. 在 wp-config.php 中强制时区(可选但推荐)

在 wp-config.php 中添加:

// 在 /* 好了,请不要再继续编辑。请保存本文件。 */ 之前添加

// 强制设置时区为亚洲/上海
date_default_timezone_set('Asia/Shanghai');

// 设置 WordPress 时区常量
define('WP_TIMEZONE', 'Asia/Shanghai');

 

 

4. 创建统一的时间函数(核心解决方案)

在主题的 functions.php 或插件中添加以下函数,整个网站统一使用这些函数获取时间:

/**
 * 统一时间处理函数
 * 整个网站所有时间相关功能都使用这个文件中的函数
 */

// 确保时区设置
if (!defined('SITE_TIMEZONE')) {
    define('SITE_TIMEZONE', 'Asia/Shanghai');
    date_default_timezone_set(SITE_TIMEZONE);
}

/**
 * 获取当前北京时间时间戳
 */
function site_current_timestamp() {
    static $current_time = null;
    if ($current_time === null) {
        $current_time = time();
    }
    return $current_time;
}

/**
 * 获取当前北京时间(Y-m-d H:i:s格式)
 */
function site_current_datetime() {
    return date('Y-m-d H:i:s', site_current_timestamp());
}

/**
 * 获取当前北京时间日期(Y-m-d格式)
 */
function site_current_date() {
    return date('Y-m-d', site_current_timestamp());
}

/**
 * 获取当前北京时间时间(H:i:s格式)
 */
function site_current_time() {
    return date('H:i:s', site_current_timestamp());
}

/**
 * 格式化时间戳为北京时间
 */
function site_format_datetime($timestamp = null) {
    if ($timestamp === null) {
        $timestamp = site_current_timestamp();
    }
    return date('Y-m-d H:i:s', $timestamp);
}

/**
 * 获取WordPress时区偏移(小时)
 */
function site_gmt_offset() {
    static $offset = null;
    if ($offset === null) {
        $offset = (float) get_option('gmt_offset');
        // 如果没有设置,默认8
        if ($offset === 0 && get_option('timezone_string') === 'Asia/Shanghai') {
            $offset = 8;
        }
    }
    return $offset;
}

/**
 * 北京时间转UTC时间戳
 */
function site_beijing_to_utc($beijing_timestamp) {
    $offset = site_gmt_offset() * HOUR_IN_SECONDS;
    return $beijing_timestamp - $offset;
}

/**
 * UTC时间戳转北京时间
 */
function site_utc_to_beijing($utc_timestamp) {
    $offset = site_gmt_offset() * HOUR_IN_SECONDS;
    return $utc_timestamp + $offset;
}

/**
 * 计算明天的某个时间(北京时间)
 */
function site_tomorrow_at($hour = 1, $minute = 0, $second = 0) {
    $tomorrow = strtotime('tomorrow ' . sprintf('%02d:%02d:%02d', $hour, $minute, $second));
    return $tomorrow;
}

 

 




相关文章




参与此文章的讨论

    很抱歉,您必须登录网站才能发布留言