138

How can I get UTC/GMT +/- time stamp using PHP's date() function? For example, if I try

date("Y-m-d H:i:s", time()); 

I will get Unix time stamp; but I need to get UTC/GMT time stamp with string GMT/UTC+/-0400 or GMT/UTC+/-1000 based on local timings.

Andrew
  • 567
  • 4
  • 16
Robin Michael Poothurai
  • 5,154
  • 7
  • 22
  • 36

14 Answers14

129

Using gmdate will always return a GMT date. Syntax is same as for date.

nikc.org
  • 15,738
  • 6
  • 46
  • 82
  • 12
    @sanmai: a Unix timestamp is by definition always UTC. https://en.wikipedia.org/wiki/Unix_time – nikc.org Jul 20 '15 at 08:20
  • 1
    @nikc.org: The problem is that gmdate("U"), returns same as time() which is not UTC timestamp if your server system timezone is different. The only way i was able to get real UTC based timestamp was strtotime(gmdate("M d Y H:i:s")), which is different that gmdate("U"), when your server system timezone is different than UTC – bksi Feb 23 '16 at 19:29
  • @bksi I'm unable to repeat your described behaviour. (My machine is not on GMT and my UNIX timestamps are correct. Also `gmdate("U") == time()`.) Sounds like potentially buggy behaviour. Double check and file a bug with the PHP project. – nikc.org Feb 24 '16 at 05:59
  • I used simple php script to test the scenario: echo time()." === ".strtotime(gmdate("M d Y H:i:s"))." Timezone: ".date("Z")."\n"; ?> When i ran it i get this result: 1456342082 === 1456338482 Timezone: 3600 The result of shell command date is: Wed Feb 24 20:28:11 CET 2016 – bksi Feb 24 '16 at 19:29
  • 2
    @bksi - Perhaps you're confusing internal representation of datetime with external representation of datetime? time w/o a zone specifier vs time with a zone specifier? As nikc (and the documentation) says, `time()` returns "number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)". Note `GMT`. The fact that by default your system *converts* this to your timezone for display, is a user convenience. Internally, its always GMT. – ToolmakerSteve Apr 17 '19 at 12:09
110

A simple gmdate() will suffice

<?php
print gmdate("Y-m-d\TH:i:s\Z");
Shankar Narayana Damodaran
  • 66,874
  • 43
  • 94
  • 124
63

As previously answered here, since PHP 5.2.0 you can use the DateTime class and specify the UTC timezone with an instance of DateTimeZone.

The DateTime __construct() documentation suggests passing "now" as the first parameter when creating a DateTime instance and specifying a timezone to get the current time.

$date_utc = new \DateTime("now", new \DateTimeZone("UTC"));

echo $date_utc->format(\DateTime::RFC850); # Saturday, 18-Apr-15 03:23:46 UTC
Jessedc
  • 11,989
  • 3
  • 49
  • 63
  • 3
    The DateTime __construct() documentation no longer suggests omitting the first parameter to get the current time. It now says you should use a string of 'now'. – PaulSkinner May 18 '18 at 11:53
  • 1
    Thanks @PaulSkinner, I have amended the answer. – Jessedc May 19 '18 at 08:24
  • Thanks, what is the purposes of the backslashes before `DateTime`? Running it myself, it seems to work just fine without them. – Snow Feb 28 '19 at 05:18
  • 1
    @Snow If this code is inserted into namespaced code, let's say your file has a `namespace A` declaration at the top, PHP will assume `DateTime` to refer to `A\DateTime`, which is wrong. Adding the backslash fixes the issue. It's a good habit to take even if you don't use namespaces yet, in my opinion. – sylbru Mar 02 '19 at 14:59
35
$time = time();
$check = $time+date("Z",$time);
echo strftime("%B %d, %Y @ %H:%M:%S UTC", $check);
Pops
  • 29,209
  • 36
  • 130
  • 150
Sudhir Bastakoti
  • 97,363
  • 15
  • 155
  • 158
24

Obtaining UTC date

gmdate("Y-m-d H:i:s");

Obtaining UTC timestamp

time();

The result will not be different even you have date_default_timezone_set on your code.

StefansArya
  • 2,494
  • 3
  • 21
  • 23
  • @زياد Thanks for the correction, I have modified my answer – StefansArya Apr 26 '19 at 03:34
  • I thought that gmdate() returns GMT and not UTC. "Identical to the date() function except that the time returned is Greenwich Mean Time (GMT)". Am I missing something? Do these come out equivalent? – Jordan Aug 16 '19 at 21:46
  • 3
    @Jordan In practice UTC and GMT represent the same time. https://stackoverflow.com/questions/48942916/difference-between-utc-and-gmt – martti Aug 24 '19 at 19:40
  • 1
    Of course `time()` returns an integer, while `gmdate` returns a formatted string. So they are only "not different" if you are careful how you use them. Technically, that `gmdate` syntax is identical to `gmdate("Y-m-d H:i:s", time());` That is, by default, the time which is formatted is `time()`. – ToolmakerSteve Jun 08 '21 at 17:01
16
date("Y-m-d H:i:s", time() - date("Z"))
Allanrbo
  • 2,188
  • 1
  • 22
  • 26
13

Other than calling gmdate you can also put this code before your rest of the code:

<?php
date_default_timezone_set("UTC");
?>

That will make rest of your date/time related calls to use GMT/UTC timezone.

anubhava
  • 713,503
  • 59
  • 514
  • 593
6

You can use gmmktime function without arguments to obtain the current UTC timestamp:

$time = gmmktime();
echo date("Y-m-d H:i:s", $time); 

gmmktime will only work if your server time is using UTC. For example, my server is set to US/Pacific. the listed function above echos back Pacific time.

ocirocir
  • 2,933
  • 1
  • 21
  • 32
4

with string GMT/UTC +/-0400 or GMT/UTC +/-1000 based on local timings

Your custom format is just missing O to give you the timezone offsets from local time.

Difference to Greenwich time (GMT) in hours Example: +0200

date_default_timezone_set('America/La_Paz');
echo date('Y-m-d H:i:s O');

2018-01-12 12:10:11 -0400

However, for maximized portability/interoperability, I would recommend using the ISO8601 date format c

date_default_timezone_set('America/La_Paz');
echo date('c');

2018-01-12T12:10:11-04:00

date_default_timezone_set('Australia/Brisbane');
echo date('c');

2018-01-13T02:10:11+10:00

You can use also gmdate and the timezone offset string will always be +00:00

date_default_timezone_set('America/La_Paz');
echo gmdate('c');

2018-01-12T16:10:11+00:00

date_default_timezone_set('Australia/Brisbane');
echo gmdate('c');

2018-01-12T16:10:11+00:00

Jeff Puckett
  • 33,491
  • 16
  • 111
  • 160
1

You can use following to get UTC time:

date_default_timezone_set('Asia/Calcutta');

$current_date = date("Y/m/d g:i A");

$ist_date = DateTime::createFromFormat(
                        '"Y/m/d g:i A"',
                        $current_date,
                        new DateTimeZone('Asia/Calcutta')
                    );

$utc_date = clone $ist_date;
$utc_date->setTimeZone(new DateTimeZone('UTC'));

echo 'UTC:  ' . $utc_date->format('Y-m-d g:i A');
danidee
  • 8,840
  • 2
  • 33
  • 55
Dalip
  • 126
  • 1
  • 9
0
/**
     * Converts a local Unix timestamp to GMT
     *
     * @param   int Unix timestamp
     * @return  int
     */
    function local_to_gmt($time = '')
    {
        if ($time === '')
        {
            $time = time();
        }

        return mktime(
            gmdate('G', $time),
            gmdate('i', $time),
            gmdate('s', $time),
            gmdate('n', $time),
            gmdate('j', $time),
            gmdate('Y', $time)
        );
    }
realmag777
  • 1,952
  • 1
  • 23
  • 19
0

You'd like to use gmdate method to get GMT date.

gmdate("Y-m-d H:i:s");

gmdate date-formats resemble those in the date() method.

quinny
  • 564
  • 1
  • 5
  • 23
ZhaoRachi
  • 9
  • 6
0

$code->created_at->setTimezone('UTC')

here $code->created_at = Asia/Dhaka Time.

JOY KUMAR PAL
  • 91
  • 1
  • 5
-1

Below find the PHP code to get current UTC(Coordinated Universal Time) time

<?php
// Prints the day
echo gmdate("l") . "<br>";

// Prints the day, date, month, year, time, AM or PM
echo gmdate("l jS \of F Y h:i:s A");
?>
Shivasagar
  • 185
  • 1
  • 2
  • 1
    The OP states: "I need to get UTC/GMT time stamp with string GMT/UTC+/-0400", and if I run the given code, the output does not contain this. Also, the OP stated that he wanted to use `date` for this, which your codes does not contain either. – Nico Haase Jun 01 '21 at 09:34