(PHP 4, PHP 5)
gmdate — 格式化一个 GMT/UTC 日期/时间
$format
[, int $timestamp
] )同 date() 函数完全一样,只除了返回的时间是格林威治标准时(GMT)。例如当在中国(GMT +0800)运行以下程序时,第一行显示“Jan 01 2000 00:00:00”而第二行显示“Dec 31 1999 16:00:00”。
Example #1 gmdate() 例子
<?php
echo date("M d Y H:i:s", mktime (0,0,0,1,1,2000));
echo gmdate("M d Y H:i:s", mktime (0,0,0,1,1,2000));
?>
Note:
在 PHP 5.1.0 之前,负的时间戳(1970 年之前的日期)在某些系统下(例如 Windows)不能工作。
参见 date(), mktime(), gmmktime() 和 strftime()。
Robert Lozyniak (2013-06-26 00:07:52)
If you want to handle years past 2038 and/or show microseconds, use this substitute:
function fgmdate($f, $t = NULL) {
// like gmdate, but accepts fractional timestamps
// and has no problem with years past 2038
if (is_null($t)) $t = microtime(true);
$days = (int)($t/86400);
$secs = $t - $days*86400;
if ($secs<0) { $days--; $secs+=86400; }
$usec = $secs; $secs = (int)$secs; $usec-=$secs;
$usec = (int)(($usec*1000000)+0.5);
if ($usec>999999) { $usec=0; $secs++; }
if ($secs>86399) { $secs=0; $days++; }
$hh = (int)($secs/3600); $mi = (int)(($secs%3600)/60);
$ss = $secs%60; $pm = ($hh>=12); $hx = $hh%12; if ($hx==0) $hx=12;
$beat = ($secs+3600)*10+(int)($usec/100000);
$beat = (int)($beat/864)%1000;
$abc = array();
$abc['e'] = 'UTC'; $abc['I'] = '0'; $abc['O'] = '+0000';
$abc['P'] = '+00:00'; $abc['T'] = 'GMT'; $abc['Z'] = '0';
$abc['a'] = $pm ? 'pm' : 'am'; $abc['A'] = $pm ? 'PM' : 'AM';
$abc['B'] = ($beat<100?'0':'').($beat<10?'0':'').$beat;
$abc['g'] = ''.$hx; $abc['G'] = ''.$hh;
$abc['h'] = ($hx<10?'0':'').$hx; $abc['H'] = ($hh<10?'0':'').$hh;
$abc['i'] = ($mi<10?'0':'').$mi; $abc['s'] = ($ss<10?'0':'').$ss;
$abc['u'] = ($usec<100000?'0':'').($usec<10000?'0':'').
($usec<1000?'0':'').($usec<100?'0':'').($usec<10?'0':'').$usec;
$rdays = $days + 280872; $wd = $rdays % 7;
$iwd = $wd; if ($iwd==0) $iwd = 7;
$yyyy = 1201; $ddd = $rdays;
$yyyy += 400*(int)($ddd/146097); $ddd %= 146097;
if ($ddd) {
while ($ddd>36524) { $yyyy+=100; $ddd-=36524; }
$yyyy += 4*(int)($ddd/1461); $ddd %= 1461;
if ($ddd) { while ($ddd>365) { $yyyy++; $ddd-=365; } }
else { $yyyy--; $ddd=366; }
}
else { $yyyy--; $ddd=366; }
$leap = (($yyyy%100==0)?($yyyy%400==0):($yyyy%4==0));
$ycal = array(1 => 31,28,31,30,31,30, 31,31,30,31,30,31);
if ($leap) $ycal[2]++;
$mm = 1; $dd = $ddd; while ($dd>$ycal[$mm]) { $dd-=$ycal[$mm]; $mm++; }
$mlen = $ycal[$mm]; $wkyr = $yyyy; $wch = $ddd - $iwd + 10;
$ww = (int)($wch/7);
if ($wch > ($leap?372:371)) { $wkyr++; $ww = 1; }
else if ($wch < 7) {
$wkyr--; $wch += ((($wkyr%100==0)?($wkyr%400==0):($wkyr%4==0))?366:365);
$ww = (int)($wch/7);
}
$yy = $yyyy % 100;
$dzero = $ddd - 1;
$mlist = array(1 => "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December");
$wlist = array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday");
$slist = array("th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th");
$suff = ((($dd<10)||($dd>20)) ? $slist[$dd%10] : 'th');
$abc['Y'] = ''.$yyyy;
$abc['y'] = ($yy<10?'0':'').$yy;
$abc['L'] = ($leap?'1':'0');
$abc['n'] = ''.$mm;
$abc['m'] = ($mm<10?'0':'').$mm;
$abc['F'] = $mlist[$mm];
$abc['M'] = substr($mlist[$mm],0,3);
$abc['t'] = ''.$mlen;
$abc['o'] = ''.$wkyr;
$abc['W'] = ($ww<10?'0':'').$ww;
$abc['z'] = ''.$dzero;
$abc['j'] = ''.$dd;
$abc['d'] = ($dd<10?'0':'').$dd;
$abc['S'] = $suff;
$abc['w'] = ''.$wd;
$abc['l'] = $wlist[$wd];
$abc['D'] = substr($wlist[$wd],0,3);
$abc['N'] = ''.$iwd;
$abc['c'] = $abc['Y'].'-'.$abc['m'].'-'.$abc['d'].'T'.
$abc['H'].':'.$abc['i'].':'.$abc['s'].$abc['P'];
$abc['r'] = $abc['D'].', '.$abc['d'].' '.$abc['M'].' '.$abc['Y'].' '.
$abc['H'].':'.$abc['i'].':'.$abc['s'].' '.$abc['O'];
$abc['U'] = ''.($days*86400+$secs);
$fa = str_split($f); $fac = count($fa);
$pos = 0;
while ($pos < $fac) {
if ($fa[$pos]=='\\') { $fa[$pos] = ''; $pos+=2; }
else if (array_key_exists($fa[$pos],$abc)) {
$fa[$pos] = $abc[$fa[$pos]]; $pos++;
}
else $pos++;
}
$out = implode($fa);
return $out;
}
RPaseur at NationalPres dot org (2009-07-25 12:51:02)
Greenwich Mean Time has no "Summer Time" or "Daylight Saving Time" so depending on the season of the year these statements may produce the same or different output.
<?php
date_default_timezone_set('Europe/London');
echo gmdate('c');
echo date('c');
?>
QED2000 (2008-08-07 11:14:47)
Here is a very simple UTC timestamp:
<?php
print gmdate("Y-m-d\TH:i:s\Z");
?>
Glen (2007-12-04 16:32:34)
This routine can help obtain a UTC timestamp:
<?php
$utc_str = gmdate("M d Y H:i:s", time());
$utc = strtotime($utc_str);
?>
Note that gmmktime(), mktime() and time() all return the same value (with no params). This was the cleanest way I found to create a UTC timestamp.
jhechtf at gmail dot com (2007-07-24 20:19:21)
My function for something like this is like so:
<?php
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.
Blazeme (2007-06-15 03:25:34)
Here, I wrote a function (from code above) for easy time zone
settings.
Regards.
<?php
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 ($daylight_saving){
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);
if($datum==true) {
return $gmdate;
}
else {
return $timestamp;
}
}
?>
If you set first argument to true, it'll return formated date.
If false, will return $timestamp.
Enjoy!
code at ashleyhunt dot co dot uk (2007-03-27 18:53:06)
I wanted to get the time past from two MySQL dates and came up with this code that does the trick.
Supply a start date, end date and optional output date/time format the default is in seconds but will expand from SS to MM:SS and then to HH:MM:SS automatically, you may wish to force a date format that will not be dynamic (site layout etc). See examples below, also see function date() for more date format options.
<?php
function calculate_time_past($start_time, $end_time, $format = "s") {
$time_span = strtotime($end_time) - strtotime($start_time);
if ($format == "s") { // is default format so dynamically calculate date format
if ($time_span > 60) { $format = "i:s"; }
if ($time_span > 3600) { $format = "H:i:s"; }
}
return gmdate($format, $time_span);
}
$start_time = "2007-03-28 00:50:14"; // 00:50:14 will work on its own
$end_time = "2007-03-28 00:52:59"; // 00:52:59 will also work instead
echo calculate_time_past($start_time, $end_time) . "<br />"; // will output 02:45
echo calculate_time_past($start_time, $end_time, "H:i:s"); // will output 00:02:45 when format is overridden
?>
I hope it of use.
Regards,
Ashley
derek at d3swimming dot com (2006-11-13 20:30:12)
I don't really know what I'm doing, so I just stole various parts of this from other people around here and did a little improvising on my own. Hope this is helpful to somebody.
This script allows you to insert just three variables: direction from GMT to your timezone ($sign), number of hours to your timezone ($h), and whether or not you have daylight savings time ($dst). The rest, including daylight savings time, will take care of itself (unless I don't know what I'm doing!).
<?php
// Get info about time zone relationship to GMT at: http://wwp.greenwichmeantime.com/
// SELECT TIME ZONE
$sign = "-"; // Whichever direction from GMT to your timezone.
$h = "8"; // Hour for time zone goes here e.g. +8 or -4, just remove the + or -
$dst = "true"; // Just insert "true" if your location uses daylight savings time or "false" if it does not
// DETECT AND ADJUST FOR DAYLIGHT SAVINGS TIME
if ($dst) {
$daylight_saving = date('I');
if ($daylight_saving){
if ($sign == "-"){ $h=$h-1; }
else { $h=$h+1; }
}
}
// FIND DIFFERENCE FROM GMT
$hm = $h * 60;
$ms = $hm * 60;
// SET CURRENT TIME
if ($sign == "-"){ $timestamp = time()-($ms); }
else { $timestamp = time()+($ms); }
// SAMPLE OUTPUT
$gmdate = gmdate("m/d/Y g:i:s A", $timestamp);
echo "Your current time now is : $gmdate . ";
?>
ttech5593 at gmail dot com (2006-03-28 14:53:49)
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 (2006-03-11 13:54:20)
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 (2005-12-28 05:35:42)
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 (2005-11-24 23:00:56)
Here's a nifty little function that returns a random timestamp between two dates.
<?php
//////////////////////////////////////////////////////////
// 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;
}
?>
rob at geek dot co dot nz (2005-11-07 12:06:50)
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 (2005-09-23 01:16:33)
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:
<?php
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 (2005-05-20 04:21:08)
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",$city_time); //echo the formatted date
echo " h. in the beautiful city of ".$city["Name"];
?>
Kogik inc dot -- info at kogik dot com (2004-07-08 14:35:14)
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 :
<?php
$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.
www.l-serwis.wpt.pl (2003-11-13 13:51:21)
If you want to get time in your timezone try this:
<?php
$zone=3600*0 //GMT
$zone=3600*1 //CET
$zone=3600*-5//USA
$date=gmdate("D M Y H:i", time() + $zone);
?>
(2002-09-08 09:26:48)
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:
<?php
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:
<?php
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");
?>
(2002-06-14 20:09:26)
For an RFC 1123 (HTTP header date) date, try:
<?php
$rfc_1123_date = gmdate('D, d M Y H:i:s T', time());
?>