102

我需要一种简单的方法来将日期时间戳转换为 UTC(从服务器所在的任何时区)希望不使用任何库。

4

16 回答 16

122

使用strtotime从给定的字符串(解释为本地时间)生成时间戳,并使用gmdate将其作为格式化的 UTC 日期返回。

例子

根据要求,这是一个简单的示例:

echo gmdate('d.m.Y H:i', strtotime('2012-06-28 23:55'));
于 2010-01-19T18:06:45.513 回答
75

使用日期时间:

$given = new DateTime("2014-12-12 14:18:00");
echo $given->format("Y-m-d H:i:s e") . "\n"; // 2014-12-12 14:18:00 Asia/Bangkok

$given->setTimezone(new DateTimeZone("UTC"));
echo $given->format("Y-m-d H:i:s e") . "\n"; // 2014-12-12 07:18:00 UTC
于 2014-12-12T07:24:33.327 回答
35

尝试getTimezone 和 setTimezone,请参阅示例

(但这确实使用了一个类)

更新:

没有任何课程,你可以尝试这样的事情:

$the_date = strtotime("2010-01-19 00:00:00");
echo(date_default_timezone_get() . "<br />");
echo(date("Y-d-mTG:i:sz",$the_date) . "<br />");
echo(date_default_timezone_set("UTC") . "<br />");
echo(date("Y-d-mTG:i:sz", $the_date) . "<br />");

注意:您可能还需要将时区设置回原始时区

于 2010-01-19T18:08:35.510 回答
27

这样做:

gmdate('Y-m-d H:i:s', $timestamp)

或者干脆

gmdate('Y-m-d H:i:s')

在UTC中获得“现在”。

检查参考:

http://www.php.net/manual/en/function.gmdate.php

于 2011-07-03T05:32:11.013 回答
15

如果您有一个格式为 YYYY-MM-HH dd:mm:ss 的日期,您实际上可以通过在“日期时间字符串”的末尾添加一个 UTC 并使用 strtotime 来转换它来欺骗 php。

date_default_timezone_set('Europe/Stockholm');
print date('Y-m-d H:i:s',strtotime("2009-01-01 12:00"." UTC"))."\n";
print date('Y-m-d H:i:s',strtotime("2009-06-01 12:00"." UTC"))."\n";

这将打印:

2009-01-01 13:00:00
2009-06-01 14:00:00

正如你所看到的,它也解决了夏令时问题。

解决它的一个有点奇怪的方法.... :)

于 2010-02-14T21:50:01.293 回答
12

将本地时区字符串转换为 UTC 字符串。
例如新西兰时区

$datetime = "2016-02-01 00:00:01";
$given = new DateTime($datetime, new DateTimeZone("Pacific/Auckland"));
$given->setTimezone(new DateTimeZone("UTC"));
$output = $given->format("Y-m-d H:i:s"); 
echo ($output);
  • NZDT: UTC+13:00
    如果 $datetime = "2016-02-01 00:00:01", $output = "2016-01-31 11:00:01";
    如果 $datetime = "2016-02-29 23:59:59", $output = "2016-02-29 10:59:59";
  • NZST: UTC+12:00
    如果 $datetime = "2016-05-01 00:00:01", $output = "2016-04-30 12:00:01";
    如果 $datetime = "2016-05-31 23:59:59", $output = "2016-05-31 11:59:59";

https://en.wikipedia.org/wiki/Time_in_New_Zealand

于 2016-05-04T05:32:43.940 回答
9

如果您不介意使用自 PHP 5.2.0 起提供的 PHP 的DateTime类,那么有几种情况可能适合您的情况:

  1. 如果您有一个$givenDt要转换为 UTC 的 DateTime 对象,那么这会将其转换为 UTC:

    $givenDt->setTimezone(new DateTimeZone('UTC'));
    
  2. 如果您$givenDt以后需要原始对象,您可能还想在转换克隆对象之前克隆给定的 DateTime 对象:

    $utcDt = clone $givenDt;
    $utcDt->setTimezone(new DateTimeZone('UTC'));
    
  3. 如果您只有一个日期时间字符串,例如$givenStr = '2018-12-17 10:47:12',那么您首先创建一个日期时间对象,然后对其进行转换。请注意,这假设它$givenStr位于 PHP 配置的时区中。

    $utcDt = (new DateTime($givenStr))->setTimezone(new DateTimeZone('UTC'));
    
  4. 如果给定的 datetime 字符串与 PHP 配置中的时区不同,则通过提供正确的时区来创建 datetime 对象(请参阅PHP 支持的时区列表)。在此示例中,我们假设阿姆斯特丹的本地时区:

    $givenDt = new DateTime($givenStr, new DateTimeZone('Europe/Amsterdam'));
    $givenDt->setTimezone(new DateTimeZone('UTC'));
    
于 2018-12-17T10:00:49.287 回答
4

我有时使用这种方法:

// It is not importnat what timezone your system is set to.
// Get the UTC offset in seconds:
$offset = date("Z");

// Then subtract if from your original timestamp:
$utc_time = date("Y-m-d H:i:s", strtotime($original_time." -".$offset." Seconds"));

大部分时间 在工作。

于 2012-04-16T14:46:40.647 回答
4

由于strtotime需要特定的输入格式,可以使用DateTime::createFromFormat (需要 php 5.3+

// set timezone to user timezone
date_default_timezone_set($str_user_timezone);

// create date object using any given format
$date = DateTime::createFromFormat($str_user_dateformat, $str_user_datetime);

// convert given datetime to safe format for strtotime
$str_user_datetime = $date->format('Y-m-d H:i:s');

// convert to UTC
$str_UTC_datetime = gmdate($str_server_dateformat, strtotime($str_user_datetime));

// return timezone to server default
date_default_timezone_set($str_server_timezone);
于 2012-08-18T19:17:29.573 回答
1

对于 PHP 5 或更高版本,您可以使用datetime::format函数(请参阅文档http://us.php.net/manual/en/datetime.format.php

 echo strftime( '%e %B %Y' , 
    date_create_from_format('Y-d-m G:i:s', '2012-04-05 11:55:21')->format('U')
    );  // 4 May 2012
于 2012-08-09T11:05:48.410 回答
1

http://php.net/manual/en/function.strtotime.php或者如果您不需要使用字符串而是时间组件,那么http://us.php.net/manual/en/function.mktime。 php

于 2010-01-19T18:06:54.107 回答
0

尝试

echo date('F d Y', strtotime('2010-01-19 00:00:00'));

将输出:

2010 年 1 月 19 日

您应该更改格式时间以查看其他输出

于 2011-10-18T16:42:10.443 回答
0

通用规范化功能,用于将任何时间戳从任何时区格式化为其他时区。对于在关系数据库中存储来自不同时区的用户的日期时间戳非常有用。对于数据库比较,将时间戳存储为 UTC 并与gmdate('Y-m-d H:i:s')

/**
 * Convert Datetime from any given olsonzone to other.
 * @return datetime in user specified format
 */

function datetimeconv($datetime, $from, $to)
{
    try {
        if ($from['localeFormat'] != 'Y-m-d H:i:s') {
            $datetime = DateTime::createFromFormat($from['localeFormat'], $datetime)->format('Y-m-d H:i:s');
        }
        $datetime = new DateTime($datetime, new DateTimeZone($from['olsonZone']));
        $datetime->setTimeZone(new DateTimeZone($to['olsonZone']));
        return $datetime->format($to['localeFormat']);
    } catch (\Exception $e) {
        return null;
    }
}

用法:

$from = ['localeFormat' => "d/m/Y H:i A", 'olsonZone' => 'Asia/Calcutta'];

$to = ['localeFormat' => "Y-m-d H:i:s", 'olsonZone' => 'UTC'];

datetimeconv("14/05/1986 10:45 PM", $from, $to); // returns "1986-05-14 17:15:00"
于 2016-12-09T05:26:50.260 回答
0

或者你可以试试这个:

<?php echo (new DateTime("now", new DateTimeZone('Asia/Singapore')))->format("Y-m-d H:i:s e"); ?>

这将输出:

2017-10-25 17:13:20 亚洲/新加坡

如果您只想显示只读日期,则可以在文本输入框的 value 属性中使用它。

如果您不想显示您的地区/国家,请删除“e”。

于 2017-10-25T09:16:33.417 回答
0

作为对Phill Pafford 答案的改进(我不理解他的 'Yd-mTG:i:sz',他建议恢复时区)。所以我提出了这个(我通过改变纯文本/文本的 HMTL 格式来复杂化......):

<?php
header('content-type: text/plain;');
$my_timestamp = strtotime("2010-01-19 00:00:00");

// stores timezone
$my_timezone = date_default_timezone_get();
echo date(DATE_ATOM, $my_timestamp)."\t ($my_timezone date)\n";

// changes timezone
date_default_timezone_set("UTC");
echo date("Y-m-d\TH:i:s\Z", $my_timestamp)."\t\t (ISO8601 UTC date)\n";
echo date("Y-m-d H:i:s", $my_timestamp)."\t\t (your UTC date)\n";

// reverts change
date_default_timezone_set($my_timezone);
echo date(DATE_ATOM, $my_timestamp)."\t ($my_timezone date is back)\n"; 
?>
于 2017-09-11T17:31:07.730 回答
0

按照以下步骤获取用户本地系统中设置的任何时区的UTC 时间(Web 应用程序需要将不同的时区保存为 UTC):

  1. Javascript(客户端):

    var dateVar = new Date();
    var offset = dateVar.getTimezoneOffset();
    //getTimezoneOffset - returns the timezone difference between UTC and Local Time
    document.cookie = "offset="+offset;
    
  2. PHP(服务器端):

    public function convert_utc_time($date)
    {
        $time_difference = isset($_COOKIE['offset'])?$_COOKIE['offset']:'';
        if($time_difference != ''){
            $time = strtotime($date);
            $time = $time + ($time_difference*60); //minutes * 60 seconds
            $date = date("Y-m-d H:i:s", $time);
        } //on failure of js, default timezone is set as UTC below
        return $date;
    }
    ..
    ..
    //in my function
    $timezone = 'UTC';
    $date = $this->convert_utc_time($post_date); //$post_date('Y-m-d H:i:s')
    echo strtotime($date. ' '. $timezone)
    
于 2018-11-09T10:16:33.610 回答