(PHP 4, PHP 5)

gmdateФорматирует дату/время по Гринвичу


string gmdate ( string $format [, int $timestamp = time() ] )

Эта функция идентична функции date() за исключением того, что возвращает время по Гринвичу (GMT).

Список параметров


Формат выводимой даты, string. Смотрите параметры форматирования для функции date().


Необязательный параметр timestamp представляет собой integer метку времени, по умолчанию равную текущему локальному времени, если timestamp не указан. Другими словами, значение по умолчанию равно результату функции time().

Возвращаемые значения

Возращает строку с форматированной датой. Если для параметра timestamp указано нечисловое значение, то будет возращено FALSE и вызвана ошибка уровня E_WARNING.

Список изменений

Версия Описание
5.1.0 Корректным диапазоном временных меток обычно является диапазон дат с 13 декабря 1901 20:45:54 GMT до 19 января 2038 03:14:07 GMT. (Эти даты соответствуют минимальному и максимальному значению 32-битному целому числу со знаком). Однако, до PHP 5.1.0 на некоторых системах (например, Windows) этот диапазон был ограничен датами от 01-01-1970 до 19-01-2038.
5.1.1 Существуют также полезные константы стандартных форматов даты/времени, которые могут быть использованы в качестве параметра format.


Пример #1 Пример использования gmdate()

Например, в Финляндии (GMT +0200), первая строка в следующем примере выведет "Jan 01 1998 00:00:00", а вторая - "Dec 31 1997 22:00:00".

echo date("M d Y H:i:s"mktime(000111998));
gmdate("M d Y H:i:s"mktime(000111998));

Смотрите также

  • date() - Форматирует вывод системной даты/времени
  • mktime() - Возвращает метку времени Unix для заданной даты
  • gmmktime() - Возвращает метку времени Unix для времени по Гринвичу
  • strftime() - Форматирует текущую дату/время с учетом текущих настроек локали


For an RFC 1123 (HTTP header date) date, try:

gmdate('D, d M Y H:i:s T'time());
2002-06-14 23:09:26
Do not use the "T" timezone specifier to generate "GMT", as this may return "UTC" or "GMT+0000" or "Z" or something else which depends on the running platform, which would not be RFC1123 compliant.

Use 'D, d M Y H:i:s \G\M\T' which forces the value of the timezone indicator.

Note that RFC1123 requires the use of ENGLISH day and month abbreviations. They MUST NOT be localized!

An example of the RFC1123 format for full dates is:
Sun, 06 Nov 1994 08:49:37 GMT

Note the presence of the leading 0 (RFC1123 dates have a fixed size, and space padding is prohibited because it causes problems with fixed size handling when such dates are used in HTTP headers that may compress whitespaces.

Some proxies accept also the ISO 8601 format, but this is not documented in HTTP/1.1 specs (RFC2616).

('Date: '.gmdate('D, d M Y H:i:s \G\M\T'time()));
header('Last-Modified: '.gmdate('D, d M Y H:i:s \G\M\T'time()));
header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T'time() + 3600));

or if you prefer double quotes and don't want to bother with double backslashes:
("Date: ".gmdate("D, d M Y H:i:s"time())." GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s"time())." GMT");;
header("Expires: ".gmdate("D, d M Y H:i:s"time() + 3600)." GMT");
2002-09-08 12:26:48
If you want to get time in your timezone try this:

$date=gmdate("D M Y H:i"time() + $zone);
2003-11-13 15:51:21
Wath out for summer time and winter time...

If you want to get the current date and time based on GMT you could use this :

= -5//(GMT -5:00) EST (U.S. & Canada)
echo gmdate("Y/m/j H:i:s"time() + 3600*($timezone+date("I"))); 

this would gives: 2004/07/8 14:35:19 in summer time
and 2004/07/8 13:35:19 in winter time.

Note that date("I") returns 1 in summer and 0 in winter.
2004-07-08 17:35:14
Want to put different International Times in your web?

First create a database including the GMT and the DST (find it f.i. at Be careful, because there are several different DST dates and options.

Once you have your function which calculates the GMT hour difference (it can be a decimal!!), sum it to the Unix Time (remember that unix time is GMT, not local: f.i. gmdate("U")===date("U)).

Don't forget to recalculate the GMT difference to seconds before it.

Then format your date using gmdate() (not date()!) and... you've got your International Time!


["Name"] = "Barcelona";
$city["GMT"] = 1.0;
$city["actualDST"] = 1.0//Because it's summer time

$gmt_diff $city["GMT"]+$city["actualDST"]; //your functions for getting the hour difference betweer the city and the GMT
$city_time time()+($gmt_diff*3600); //sum the timestamps
echo gmdate("H:i",$city_time); //echo the formatted date
echo " h. in the beautiful city of ".$city["Name"];

2005-05-20 07:21:08
Gives user the ability to use their timezone preferences.
I had to create this script for a very large community. I first made any posts to the database that would display the date using just time();

Example: mysql_query("INSERT INTO `table` (`datetime`) VALUES ('".time()."')");

Also, for their timezone preference, I had the values as (example):
(Eastern Timezone) -5 hours
(Newfoundland) -3 hours -30 minutes

This information would be saved in the users table.
To display the date and time in their respective timezone preference:

function datetime($datetime,$zone){
gmdate('m-d-Y - h:i:sa',strtotime($zone,$datetime));

$datetime would be the information pulled from the database from a post for news, forums, etcetera (remember, the inserted table data for the time was using time();)
$zone would be the information pulled from the database from the users timezone preference.

I also used cookies to store their timezone:
$sth=mysql_query("SELECT `datetime` FROM `table` LIMIT 1");
echo datetime($row['datetime'],$_COOKIE['timezone']);

Remember to set the 'm-d-Y - h:i:sa' to how you wish the time to display. Visit the manual about date().
2005-09-23 04:16:33
It's worth noting the distinction between gmgate() and date() with regards to day light savings time. If your server uses universal time and makes an adjustment by locale for daylight savings time, you will want to use date(). gmdate will display the non-adjuisted time.
2005-11-07 14:06:50
Here's a nifty little function that returns a random timestamp between two dates.

// Return a random timestamp between two dates (inclusive)
// Example: Tue, 08 Nov 2004 06:47:10 GMT
// time - Starting time string
// Valid Examples:
// 10 September 2001
// next Thursday
// last Monday
// now
// time2 - Ending time string
function randomTimestamp($time "" $time2 "")
$time$time strtotime("10 September 2000");
$time2$time2 strtotime("24 November 2005");
$timestamp date(" D, d M Y"randsettype($time int) , settype($time2 int) )); //Must be called once before becoming random, ???
$timestamp date(" D, d M Y"rand($time $time2))." ";//Now it's random
$h rand(1,23);
strlen($h) == $h "0$h";
$t $h.":";
$d rand(1,29);
strlen($d) == $d "0$d";
$t .= $d.":";
$s rand(0,59);
strlen($s) == $s "0$s";
$t .= $s;
$timestamp .= $t." GMT";
2005-11-25 01:00:56
If you have the same application running in different countries, you may have some troubles getting the local time..
In my case, I was having troubles with a clock created with Macromedia Flash... the time shown by the clock was supposed to be set up by the server, passing the timestamp. When I moved the file to another country, I got a wrong time...
You can use the timezone offset ( date("Z") ) to handle this kind of thing...

gmdate("Y/m/d H:i:s",$timestamp);
2005-12-28 07:35:42
I was struggling with how to get my browser to output MY local time using gmdate().

I figured it out and here's what you do (ASSUMING THE SERVER IS ON GMT, If not, just echo a generic gmdate() without timezone setting and calculate the number of hours ahead or behind you are of that time, convert it to seconds and add [for ahead] or subtract [for behind] that value to time() ):

NOTE: these are US times [setlocale(LC_TIME, 'en_US')]

for Central Time (7 hours behind GMT):
gmdate("format", time()-(25200));

For Pacific Time (9 hours behind GMT):
gmdate("format", time()-(32400));


I used the following gmdate() format:
"l, F jS, Y  g:i a"
but you can use what you like ;)

Hope this helps!
2006-03-11 15:54:20
For me most of the examples here needed the + or - seconds to set the time zone. I wanted a faster way to get the time zone in seconds. So I created this : 
"3";// Hour for time zone goes here e.g. +7 or -4, just remove the + or -
$hm $h 60
$ms $hm 60;
$gmdate gmdate("m/d/Y g:i:s A"time()-($ms)); // the "-" can be switched to a plus if that's what your time zone is.
echo "Your current time now is :  $gmdate . ";
It works. Hope it helps.
2006-03-28 17:53:49
Here, I wrote a function (from code above) for easy time zone
function datum($datum=true) {
$sign "+"// Whichever direction from GMT to your timezone. + or -
$h "1"// offset for time (hours)
$dst true// true - use dst ; false - don't

if ($dst==true) {
$daylight_saving date('I');
    if (
        if (
$sign == "-"){ $h=$h-1;  }
        else { 
$h=$h+1; }
$hm $h 60;
$ms $hm 60;
if (
$sign == "-"){ $timestamp time()-($ms); }
else { 
$timestamp time()+($ms); }
$gmdate gmdate("m.d.Y. g:i A"$timestamp);
$datum==true) {
else {


If you set first argument to true, it'll return formated date.
If false, will return $timestamp.
2007-06-15 06:25:34
My function for something like this is like so:
function actual_time($format,$offset,$timestamp){
//Offset is in hours from gmt, including a - sign if applicable. 
   //So lets turn offset into seconds
$offset $offset*60*60;
$timestamp $timestamp $offset;
//Remember, adding a negative is still subtraction ;)
return gmdate($format,$timestamp);
It's always worked fine for me.
2007-07-24 23:19:21
Here is a very simple UTC timestamp:


print gmdate("Y-m-d\TH:i:s\Z"); 

2008-08-07 14:14:47
A function to get the ISO 8601 timestamp in UTC with precision up to microseconds

function iso_8601_utc_time($precision = 0)
    $time = gettimeofday();

    if (is_int($precision) && $precision >= 0 && $precision <= 6) {
        $total = (string) $time['sec'] . '.' . str_pad((string) $time['usec'], 6, '0', STR_PAD_LEFT);
        $total_rounded = bcadd($total, '0.' . str_repeat('0', $precision) . '5', $precision);
        @list($integer, $fraction) = explode('.', $total_rounded);
        $format = $precision == 0
            ? "Y-m-d\TH:i:s\Z"
            : "Y-m-d\TH:i:s,".$fraction."\Z";
        return gmdate($format, $integer);

    return false;
2016-08-31 14:09:07
If you want to calculate the time period between two clocked events that happen less than 24 hours apart, for example the daylight period between sunrise and sunset, you can take advantage of the fact that the gmdate() function also accepts a negative timestamp. If you want to present the time period in the format hours:minutes you can use

'7:45'// hours with or without leading zeros
$sunset_clocked '21:05'// hours with or without leading zeros

$time_past gmdate('G:i'strtotime($sunset_clocked) - strtotime($sunrise_clocked));

'Daylight period is ' $time_past ' (hours:minutes)';

The above example will output

    Daylight period is 13:20 (hours:minutes)

The fun part comes in when the sunset time is next day (and therefore in value lower than the sunrise clock time), for example:

     $sunrise_clocked = '18:45';
     $sunset_clocked = '09:30';

will output

     Daylight period is 14:45 (hours:minutes)

This trick does NOT work with date(), because the output may then be off a number of hours, depending on your time zone.
Tested with PHP 5.6.35 and 7.2.4.
2018-07-03 14:35:52
I am getting a string which is a timestamp:

string(13) "1532941682753"

I need to convert it to date in the following format: (yyyy-mm-dd hh:mm:ss.SSS) I can do it with

gmdate('yyyy-mm-dd hh:mm:ss.SSS', $timestamp)

but I get the error that 2nd argument is not an int. So I need to convert my timestamp to valid int. I tried to cast my timestamp string to int but the problem is it is too long for int and every time I get the maximum allowed for int, which is int(2147483647). Any ideas how to fix it would be welcome. Thank you.
2018-08-10 09:57:13

    Поддержать сайт на родительском проекте КГБ