gmdate

(PHP 3, PHP 4, PHP 5)

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

Описание

string gmdate ( string format [, int timestamp] )

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

Пример 1. gmdate() example

<?php
echo date("M d Y H:i:s", mktime(0, 0, 0, 1, 1, 1998));
echo
gmdate("M d Y H:i:s", mktime(0, 0, 0, 1, 1, 1998));
?>

Замечание: В семействе ОС Microsoft Windows системные библиотеки, реализующие эту функцию, содержат ошибки, поэтому функция gmdate() на этих системах не поддерживает отрицательные значения аргумента timestamp. Для более подробной информации, см. сообщения об ошибках: #22620, #22457, и #14391.

В операционных системах Unix/Linux эта проблема не возникает, так как системные библиотеки в этих системах реализованы корректно.

PHP не может исправить ошибки в системных библиотеках. Для решения этой и подобных проблем обращайтесь к производителю операционной системы.

См. также описание функций date(), mktime(), gmmktime() и strftime().



gmdate
ttech5593 at gmail dot com
28-Mar-2006 02:53
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 :
<?php
$h
= "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.
gefiltefishee at comcast dot net
11-Mar-2006 01:54
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));

REMEMBER - THE VALUES ABOVE ASSUME THE SERVER IS ON GMT

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

Hope this helps!
fernandobassani at gmail dot com
28-Dec-2005 05:35
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...

<?php
$timestamp
= time()+date("Z");
echo
gmdate("Y/m/d H:i:s",$timestamp);
?>
Sir Derek G
24-Nov-2005 11:00
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 = "")
{
   if(!
$time) $time = strtotime("10 September 2000");
   if(!
$time2) $time2 = strtotime("24 November 2005");
  
$timestamp = date(" D, d M Y", rand( settype($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);
   if(
strlen($h) == 1 ) $h = "0$h";
  
$t = $h.":";
  
  
$d = rand(1,29);
   if(
strlen($d) == 1 ) $d = "0$d";
  
$t .= $d.":";
  
  
$s = rand(0,59);
   if(
strlen($s) == 1 ) $s = "0$s";
  
$t .= $s;
  
  
$timestamp .= $t." GMT";
   return
$timestamp;
}
?>
faraz at gmail dot com
15-Nov-2005 08:40
Hi i was having a problem in converting a date to any time zone so I wrote my own function which coverts a given date and time to other time zone equivalent

function printByTimeZone($mytime,$mydate,$mytimezone)
{
  
 //assuming timezone in format +05:00 or -4:30

$conTime = $mytime;
$conDate = $mydate;

$tzonehr=substr($mytimezone,1,2);
$tzonesec=substr($mytimezone,4,2);
$sign= substr($mytimezone,0,1);

$timezone=intval($tzonehr)*60 + ( intval($tzonesec)*3600);
Switch($sign)
{
Case -:
   $timezone=$timezone*(-1);
   Break;
}

// write a method to extract your hours,min,sec,day,month,year (all should be in numeric form)

$TimeStamp= mktime($yourhours, $yourmins,$yoursecs,$yourmonth,$yourday ,$youryear ,-1);

$TimeStamp=$TimeStamp+$_GET['TimeZone'];
$GMTDateTime=gmdate("H:i:s D M d Y",$TimeStamp);
return $GMTDateTime;
}
eddie[dot_here]bishop@gmail[dot_here]com
09-Nov-2005 12:36
In response to ncofreNOSPAMPLEASE at step2u dot com,

Your international time is all well and good, but you left out a VERY important piece of the code you provided.

Change the second to last line from
   echo gmdate("H:i");
to
   echo gmdate("H:i", $city_time);

Nice example, though, thanks!
rob at geek dot co dot nz
07-Nov-2005 12:06
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.
paul at sysnyx dot com
23-Sep-2005 01:16
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){
if(date('I')):$datetime+=60*60;endif;
return 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");
$row=mysql_fetch_assoc($sth);
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().
ncofreNOSPAMPLEASE at step2u dot com
20-May-2005 04:21
Want to put different International Times in your web?

First create a database including the GMT and the DST (find it f.i. at timeanddate.com). 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!

<?php

$city
["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"); //echo the formatted date
echo " h. in the beautiful city of ".$city["Name"];

?>
chrisjj at despammed dot com
07-Oct-2004 11:33
This doc is faulty, saying:

> Identical to the date() function except that the time
> returned is Greenwich Mean Time (GMT).

where the date() function says

> T    Timezone setting of this machine

gmdate('T') does NOT return the Timezone setting of the machine. Instead it returns the machine's description of GMT, which may or may not be "GMT"
Kogik inc dot -- info at kogik dot com
08-Jul-2004 02:35
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 :

$timezone  = -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.
webmaster at rwhiphop dot com
25-May-2004 10:18
$zone=3600*2//SPAIN
$date=gmdate("D M Y H:i", time() + $zone);
www.l-serwis.wpt.pl
13-Nov-2003 01:51
If you want to get time in your timezone try this:

$zone=3600*0 //GMT
$zone=3600*1 //CET
$zone=3600*-5//USA
$date=gmdate("D M Y H:i", time() + $zone);
08-Sep-2002 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).

Examples:
header('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:
header("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");
14-Jun-2002 08:09
For an RFC 1123 (HTTP header date) date, try:

$rfc_1123_date = gmdate('D, d M Y H:i:s T', time());

<gettimeofdaygmmktime>
 Last updated: Tue, 15 Nov 2005