108

I am in need of an easy way to convert a date time stamp to UTC (from whatever timezone the server is in) HOPEFULLY without using any libraries.

Jeremey
  • 1,456
  • 3
  • 13
  • 19

16 Answers16

127

Use strtotime to generate a timestamp from the given string (interpreted as local time) and use gmdate to get it as a formatted UTC date back.

Example

As requested, here’s a simple example:

echo gmdate('d.m.Y H:i', strtotime('2012-06-28 23:55'));
poke
  • 369,085
  • 72
  • 557
  • 602
  • 2
    @cherouvim Don’t think it’s necessary, but added one anyway… Hope it helps. – poke Jun 28 '12 at 21:56
  • 8
    gmdate() is one of those PHP functions I wish I had stumbled upon a long time ago. nl2br, anyone? – Charlie Schliesser Jan 15 '13 at 22:57
  • 3
    GMT and UTC are not always the same. – Jay Sheth Oct 03 '13 at 14:56
  • 1
    @JaySheth Practically, UTC and GMT are synonymous. – poke Oct 03 '13 at 21:20
  • @poke To make your answer even more illuminating, can you show the output of your example code. – Nigel Alderton Jun 30 '14 at 21:55
  • @NigelAlderton The output depends on the timezone settings of the machine running the code. But it will be something like this: `28.06.2012 23:55`. – poke Jul 02 '14 at 14:41
  • **THIS** is the most correct answer! Disregard che accepted one! – Matteo Tassinari Aug 29 '14 at 08:13
  • Hell, the date string has specific time zone associated with it. – Shahid Karimi Jul 16 '15 at 09:47
  • @Kannu Hell yes, as the question states, the parsed date string is supposed to be interpreted as the server’s local time, which is what `strtotime` does, and then converted to a date string in UTC. Remember that the Unix timestamp is *by definition* in UTC. So whatever timezone the server had, it is incorperated by the time you call `strtotime`. – poke Jul 16 '15 at 11:26
  • @MatteoTassinari Nope, because of the strtotime. I am working on an astrology software, and what if I want to check Leonardo Da Vinci profile? He borned in 1452. strtotime can not do anything with this. DateTime is the best for this. – vaso123 Jan 05 '16 at 11:19
  • 2
    @poke GMT respects daylight saving time, UTC does not and that's why it is used so you dont have to factor anything else in – Necro Jun 12 '18 at 03:07
  • @Necro I don’t know what exactly you are responding to there but technically, GMT is the timezone at UTC+0 *without* DST. BST is UTC+0 *with* UTC. So you could say that GMT does not respect DST but instead is only a timezone without DST. – poke Jun 12 '18 at 07:54
82

Using DateTime:

$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
joerx
  • 2,028
  • 1
  • 16
  • 18
  • The question says convert a timestamp to a timestamp, and DateTime doesn't accept a timestamp as input. You would have to convert it to a string somehow then convert it back. – felwithe Feb 11 '20 at 01:41
  • 1
    DateTime does accept a timestamp as input: `new DateTime('@' . 1656627600)` – dogawaf Jul 08 '22 at 17:30
35

Try the getTimezone and setTimezone, see the example

(But this does use a Class)

UPDATE:

Without any classes you could try something like this:

$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 />");

NOTE: You might need to set the timezone back to the original as well

Phill Pafford
  • 83,471
  • 91
  • 263
  • 383
29

Do this way:

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

or simply

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

to get "NOW" in UTC.

Check the reference:

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

laurent
  • 88,262
  • 77
  • 290
  • 428
Attilio
  • 2,121
  • 2
  • 21
  • 20
17

If you have a date in this format YYYY-MM-HH dd:mm:ss, you can actually trick php by adding a UTC at the end of your "datetime string" and use strtotime to convert it.

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";

This will print this:

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

And as you can see it takes care of the daylight savings time problem as well.

A little strange way to solve it.... :)

Johan
  • 20,067
  • 28
  • 92
  • 110
12

Convert local time zone string to UTC string.
e.g. New Zealand Time Zone

$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
    if $datetime = "2016-02-01 00:00:01", $output = "2016-01-31 11:00:01";
    if $datetime = "2016-02-29 23:59:59", $output = "2016-02-29 10:59:59";
  • NZST: UTC+12:00
    if $datetime = "2016-05-01 00:00:01", $output = "2016-04-30 12:00:01";
    if $datetime = "2016-05-31 23:59:59", $output = "2016-05-31 11:59:59";

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

Frank Hou
  • 1,688
  • 1
  • 16
  • 11
12

If you don't mind using PHP's DateTime class, which has been available since PHP 5.2.0, then there are several scenarios that might fit your situation:

  1. If you have a $givenDt DateTime object that you want to convert to UTC then this will convert it to UTC:

    $givenDt->setTimezone(new DateTimeZone('UTC'));
    
  2. If you need the original $givenDt later, you might alternatively want to clone the given DateTime object before conversion of the cloned object:

    $utcDt = clone $givenDt;
    $utcDt->setTimezone(new DateTimeZone('UTC'));
    
  3. If you only have a datetime string, e.g. $givenStr = '2018-12-17 10:47:12', then you first create a datetime object, and then convert it. Note this assumes that $givenStr is in PHP's configured timezone.

    $utcDt = (new DateTime($givenStr))->setTimezone(new DateTimeZone('UTC'));
    
  4. If the given datetime string is in some timezone different from the one in your PHP configuration, then create the datetime object by supplying the correct timezone (see the list of timezones PHP supports). In this example we assume the local timezone in Amsterdam:

    $givenDt = new DateTime($givenStr, new DateTimeZone('Europe/Amsterdam'));
    $givenDt->setTimezone(new DateTimeZone('UTC'));
    
The Coprolal
  • 896
  • 8
  • 8
5

I sometime use this method:

// 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"));

Works all MOST of the time.

aorcsik
  • 15,271
  • 5
  • 39
  • 49
  • 3
    Two problems here. First you shouldn't subtract you should add the offset. Second, this doesn't work if local timezone is currently on DST and the desired date is not on DST. The offset would be off by an hour. Or Vice Versa. So yes, this works MOST of the time, but not always. – ajon Aug 21 '13 at 15:17
4

As strtotime requires specific input format, DateTime::createFromFormat could be used (php 5.3+ is required)

// 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);
1

With PHP 5 or superior, you may use datetime::format function (see documentation 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
MUY Belgium
  • 2,330
  • 4
  • 30
  • 46
1

http://php.net/manual/en/function.strtotime.php or if you need to not use a string but time components instead, then http://us.php.net/manual/en/function.mktime.php

psychotik
  • 38,153
  • 34
  • 100
  • 135
0

General purpose normalisation function to format any timestamp from any timezone to other. Very useful for storing datetimestamps of users from different timezones in a relational database. For database comparisons store timestamp as UTC and use with 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;
    }
}

Usage:

$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"
Community
  • 1
  • 1
Sandeep
  • 28,307
  • 3
  • 32
  • 24
0

As an improvement on Phill Pafford's answer (I did not understand his 'Y-d-mTG:i:sz' and he suggested to revert timezone). So I propose this (I complicated by changing the HMTL format in plain/text...):

<?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"; 
?>
7Tonin
  • 69
  • 4
0

alternatively you can try this:

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

this will output :

2017-10-25 17:13:20 Asia/Singapore

you can use this inside the value attribute of a text input box if you only want to display a read-only date.

remove the 'e' if you do not wish to show your region/country.

Bruce Tong
  • 1,366
  • 15
  • 14
0

Follow these steps to get UTC time of any timezone set in user's local system (This will be required for web applications to save different timezones to UTC):

  1. Javascript (client-side):

    var dateVar = new Date();
    var offset = dateVar.getTimezoneOffset();
    //getTimezoneOffset - returns the timezone difference between UTC and Local Time
    document.cookie = "offset="+offset;
    
  2. Php (server-side):

    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)
    
Pradeep Kumar
  • 4,065
  • 2
  • 33
  • 40
0

try

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

will output:

January 19 2010

you should change format time to see other output

StevieJ
  • 9
  • 1