ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

如何通过PHP轻松转换UTC的日期?

2019-09-26 04:40:15  阅读:506  来源: 互联网

标签:php timezone


我在UTC中的日期时间字段中将日期存储在MySQL数据库中.我正在使用PHP,并且我调用了date_timezone_set(‘UTC’),以便所有对date()的调用(没有时间戳)以UTC格式返回日期.

然后,我有它,所以给定的网站可以选择其时区.现在我希望日期显示在网站的时区.因此,如果我将日期存储为“2009-04-01 15:36:13”,则应在PDT时区(-7小时)内为用户显示为“2009-04-01 08:36:13” .

通过PHP执行此操作的最简单(最少代码)方法是什么?到目前为止,我所想到的只是

date('Y-m-d H:i:s', strtotime($Site->getUTCOffset() . ' hours', strtotime(date($utcDate))));

有更短的方式吗?

解决方法:

这是我们对服务器所做的.我们将所有内容设置为使用UTC,并通过动态转换显示在用户的时区中.这篇文章底部的代码是如何使其工作的一个例子;你应该确认它适用于所有情况下你的设置(即夏令时等).

配置CentOS

>编辑/ etc / sysconfig / clock并将ZONE设置为UTC
> ln -sf /usr/share / zoneinfo / UTC / etc / localtime

配置MySQL

>如有必要,将时区导入MySQL:

mysql_tzinfo_to_sql /usr/share / zoneinfo | mysql -u root -p mysql
>编辑my.cnf并在[mysqld]部分中添加以下内容:

default-time-zone =’UTC’

PHP代码

<?php
/*
Example usage:
  $unixtime = TimeUtil::dateTimeToTimestamp('2009-04-01 15:36:13');
  echo TimeUtil::UTCToPST("M d, Y - H:i:s", $unixtime);
*/

// You should move this to your regular init method
date_default_timezone_set('UTC'); // make this match the server timezone

class TimeUtil {
    public static function timestampToDateTime($timestamp) {
        return gmdate('Y-m-d H:i:s', $timestamp);
    }

    public static function dateTimeToTimestamp($dateTime) {
        // dateTimeToTimestamp expects MySQL format
        // If it gets a fully numeric value, we'll assume it's a timestamp
        // You can comment out this if block if you don't want this behavior
        if(is_numeric($dateTime)) {
            // You should probably log an error here
            return $dateTime;
        }
        $date = new DateTime($dateTime); 
        $ret = $date->format('U');
        return ($ret < 0 ? 0 : $ret);
    }

    public static function UTCToPST($format, $time) {
        $dst = intval(date("I", $time));
        $tzOffset = intval(date('Z', time()));
        return date($format, $time + $tzOffset - 28800 + $dst * 3600);
    }

}

标签:php,timezone
来源: https://codeday.me/bug/20190926/1818712.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有