Date/Time 函数
在线手册:中文 英文
PHP手册

localtime

(PHP 4, PHP 5)

localtime取得本地时间

说明

array localtime ([ int $timestamp [, bool $is_associative ]] )

localtime() 函数返回一个数组,其结构和 C 函数调用返回的完全一样。localtime() 的第一个参数是时间戳,如果没有给出则使用从 time() 返回的当前时间。第二个参数是 is_associative,如果设为 FALSE 或未提供则返回的是普通的数字索引数组。如果该参数设为 TRUElocaltime() 函数返回包含有所有从 C 的 localtime 函数调用所返回的不同单元的关联数组。关联数组中不同的键名为:

Note: 月份从 0(一月)到 11(十二月),星期数从 0(星期天)到 6(星期六)。

Example #1 time() 例子

<?php
$localtime 
localtime();
$localtime_assoc localtime(time(), true);
print_r($localtime);
print_r($localtime_assoc);
?>

以上例程的输出类似于:

Array
(
    [0] => 24
    [1] => 3
    [2] => 19
    [3] => 3
    [4] => 3
    [5] => 105
    [6] => 0
    [7] => 92
    [9] => 1
)

Array
(
    [tm_sec] => 24
    [tm_min] => 3
    [tm_hour] => 19
    [tm_mday] => 3
    [tm_mon] => 3
    [tm_year] => 105
    [tm_wday] => 0
    [tm_yday] => 92
    [tm_isdst] => 1
)

参数

timestamp

可选的 timestamp 参数是一个 integer 的 Unix 时间戳,如未指定,参数值默认为当前本地时间。也就是说,其值默认为 time() 的返回值。

is_associative

If set to FALSE or not supplied then the array is returned as a regular, numerically indexed array. If the argument is set to TRUE then localtime() returns an associative array containing all the different elements of the structure returned by the C function call to localtime. The names of the different keys of the associative array are as follows:

  • "tm_sec" - seconds, 0 to 59
  • "tm_min" - minutes, 0 to 59
  • "tm_hour" - hours, 0 to 23
  • "tm_mday" - day of the month, 1 to 31
  • "tm_mon" - month of the year, 0 (Jan) to 11 (Dec)
  • "tm_year" - years since 1900
  • "tm_wday" - day of the week, 0 (Sun) to 6 (Sat)
  • "tm_yday" - day of the year, 0 to 365
  • "tm_isdst" - is daylight savings time in effect? Positive if yes, 0 if not, negative if unknown.

错误/异常

在每 次调用日期/时间函数时,如果时区无效则会引发 E_NOTICE 错误,如果使用系统设定值或 TZ 环境变量,则会引发 E_STRICTE_WARNING 消息。参见 date_default_timezone_set()

更新日志

版本 说明
5.1.0

现在发布 E_STRICTE_NOTICE 时区错误。

范例

Example #2 localtime() example

<?php
$localtime 
localtime();
$localtime_assoc localtime(time(), true);
print_r($localtime);
print_r($localtime_assoc);
?>

以上例程的输出类似于:

Array
(
    [0] => 24
    [1] => 3
    [2] => 19
    [3] => 3
    [4] => 3
    [5] => 105
    [6] => 0
    [7] => 92
    [8] => 1
)

Array
(
    [tm_sec] => 24
    [tm_min] => 3
    [tm_hour] => 19
    [tm_mday] => 3
    [tm_mon] => 3
    [tm_year] => 105
    [tm_wday] => 0
    [tm_yday] => 92
    [tm_isdst] => 1
)

参见


Date/Time 函数
在线手册:中文 英文
PHP手册
PHP手册 - N: 取得本地时间

用户评论:

Chris (25-May-2011 04:26)

Sometimes, there's not a server-based/PHP method for getting local time. You have to get it from the client via Javascript.  Google "bitbucket timezone detect" and use it to set a "local_timezone" cookie that you can read from PHP and set via date_default_timezone_set()

dev2 at heesakkers dot info (30-Dec-2008 03:23)

Be aware that tm_yday also starts with 0 for the first of January.

hutch120 at gmail dot com (08-Nov-2007 01:23)

The functions shown below may help implement a timezones library.

<?php

/**
 * This function returns the server timezone offset in seconds
 * e.g. Sydney in DST returns +1100 / 100 * 60 * 60 = 39600
 */
function getServerTimeZoneOffset()
{
    return
date("O") / 100 * 60 * 60; // Seconds from GMT
}

/**
 * This function returns the local timezone offset in seconds
 *   where getTimeZone($userid) returns a timezone see below.
 */
function getLocalTimeZoneOffset($userid)
{
    return
getTimeZone($userid) / 100 * 60 * 60; // Seconds from user GMT
}

// Now converting a server timestamp to a local timestamp is very simple.

/**
 * Will take a timestamp and minus off Server GMT and add on user GMT seconds
 * thereby making a local timestamp from a server timestamp.
 */
function getLocalTimestampFromServerTimestamp($userid, $timestamp)
{
    return
$timestamp - getServerTimeZoneOffset() + getLocalTimeZoneOffset( $userid );
}

//And getting the local time from a user entered date is a useful function.
//Combine the next two functions to achieve just that.

function getLocalTimestampFromDateTime($userid, $datetime)
{
   
$timestamp = strtotime($datetime);
    return
getLocalTimestampFromServerTimestamp($userid, $timestamp);
}

/**
 * If you have a localized timestamp and just want to get the date format use this.
 */
function getFormattedDate($userid, $timestamp)
{
    return
date("Y-m-d H:i:s " . getTimeZone($userid), $timestamp);
}

/**
 * Returns a timezone in the format +0000
 *  e.g. Perth in DST returns +0900
 */
function getTimeZone($userid)
{
    return
"+0900"; // Perth in DST
}

?>

anomie at users dot sourceforge dot net (08-Dec-2006 08:22)

Here is another version of gmtime(). This one doesn't involve messing around with timezones at all. Note that PHP4 users should check out the array_combine page for replacements for that function.

<?php
function gmtime($ts=null, $is_associative=false){
    if(
is_null($ts)) $ts=time();
   
$t=array_map('intval',explode(',',gmdate('s,i,H,d,m,Y,w,z,I',$ts)));
   
$t[4]--;
   
$t[5]-=1900;
    if(!
$is_associative) return $t;
    return
array_combine(array('tm_sec','tm_min','tm_hour','tm_mday','tm_mon',
                                
'tm_year','tm_wday','tm_yday','tm_isdst'),
                      
$t);
}
?>

matt (at) roughest [d0t] net (27-Oct-2004 06:49)

Be careful with the "tm_isdst" element. It may be incorrect for certain localities where daylight savings time is not observed (for example most of Saskatchewan in Canada).

tony at speedscript dot com (24-Feb-2004 06:35)

Date select box for the current week, or whatever week you give for an offset (in seconds), returns the string you can echo with the select box named $name:

<?php
function week_date_selectbox( $time_offset, $name )
    {
    if( isset(
$time_offset ) )
       
$t = time() + $time_offset;
    else
       
$t = time();

   
$wday = array("Sun ","Mon ","Tue ","Wed ","Thu ","Fri ","Sat ");
   
$mon = array("Jan ","Feb ","Mar ","Apr ","May ","Jun ","Jul ","Aug ","Sep ","Oct ","Nov ","Dec ");
   
$mybox = "<select name=\"$name\">\n";
    for(
$ii = 0; $ii > -6; $ii--)
        {
       
$tarr = localtime( $t + $ii * 86400, 1 );
        if(
$tarr["tm_wday"] == 0 )
            {
           
// found Sunday, now make the week's strings
           
for($jj = 0; $jj < 7; $jj++)
                {
               
$tarr = localtime( $t + ($jj + $ii) * 86400, 1 );
               
$mybox .= sprintf( " <option value=\"%04d-%02d-%02d\">%s%s%d %d</option>\n",
                        ((int)
$tarr["tm_year"] + 1900),
                       
$tarr["tm_mon"],
                        ((int)
$tarr["tm_mday"] + 1),
                       
$wday[$tarr["tm_wday"]],
                       
$mon[$tarr["tm_mon"]],
                        (int)
$tarr["tm_mday"],
                        ((int)
$tarr["tm_year"] + 1900) );
                }
            break;
            }
        }
   
$mybox .= "</select>\n";

    return
$mybox;
    }
?>

!!emiliop!! AT nospam dot dorial dot com (20-Feb-2003 08:12)

To calculate the delta between the local time and UTC:

<?php
function tzdelta ( $iTime = 0 )
{
    if (
0 == $iTime ) { $iTime = time(); }
   
$ar = localtime ( $iTime );
   
$ar[5] += 1900; $ar[4]++;
   
$iTztime = gmmktime ( $ar[2], $ar[1], $ar[0],
       
$ar[4], $ar[3], $ar[5], $ar[8] );
    return (
$iTztime - $iTime );
}
?>

So if your system is in DST, tzdelta should return -18000 (five hours less).

arch at archtech dot yi dot org (09-Dec-2002 09:25)

You can implement gmtime quote simply.

<?php
function GetTZOffset() {
 
$Offset = date("O", 0);
  
 
$Parity = $Offset < 0 ? -1 : 1;
 
$Offset = $Parity * $Offset;
 
$Offset = ($Offset - ($Offset % 100))/100*60 + $Offset % 100;

  return
$Parity * $Offset;
}

$TZOffset = GetTZOffset();

$t_time = time()-$TZOffset*60; #Counter adjust for localtime()
$t_arr = localtime($t_time);
?>

static (03-Jun-2002 03:57)

Be VERY CAREFUL with the return of this function if you intend to feed it straight back into mktime(). localtime() returns months as 0 to 11, but mktime uses months as 1 to 12. The resulting off-by-one errors can be ... unpleasant.

You Have Been Warned.

Wade.

jausions-N at SPAM-hotmail dot com (26-Apr-2002 08:42)

I strongly suggest to do all of your developments using GMT/UTC dates & times.

I provide here a version of a 'gmttime' function. Save it in a separate file and include it when needed.

Please post a correction here if you find it not working for your timezone (with or without daylight saving time.).

Thanks & Enjoy.
-----------------------------------------------

<?php
//
// File: gmttime.php
//
// Description:
//    Implements the gmttime function if missing from the PHP distribution
//

// Verifies that the function isn't already implemented
if (function_exists(gmttime))
    return;

//
// Function: gmttime
//
// Description:
//   Returns an array indexed as by the localtime() function:
//   - 0 or tm_sec: Seconds
//   - 1 or tm_min: Minutes
//   - 2 or tm_hour: Hour
//   - 3 or tm_mday: Day of the month
//   - 4 or tm_mon: Month of the year
//   - 5 or tm_year: Years since 1900
//   - 6 or tm_wday: Day of the week
//   - 7 or tm_yday: Day of the year
//   - 8 or tm_isdst: Is daylight saving time in effect
//   - tm_fyear: Full year (only available with associative array)
//
// Arguments:
//   - Timestamp
//   - Boolean (for associative indexing: 0 = off, 1 = on)
//
// Returns:
//   An array on success,
//   false on failure.
//
function gmttime($dTimestamp = '', $bAssoc = 0) {
   
// Evaluate how much difference there is between local and GTM/UTC
    // Don't forget to correct for daylight saving time...
   
$aNow = localtime();
   
$iDelta = gmmktime(1, 1, 1, 1, 1, 1970, $aNow[8]) - mktime(1, 1, 1, 1, 1, 1970, $aNow[8]);

    if (!
$bAssoc) {
        if (
$dTimestamp == '') {
            return
localtime(time() - $iDelta, 0);
        } else {
            return
localtime($dTimestamp - $iDelta, 0);
        }
    } else {
       
// For associative array, add full year index
       
if ($dTimestamp == '') {
           
$aGMTTime = localtime(time() - $iDelta, 1);
        } else {
           
$aGMTTime = localtime($dTimestamp - $iDelta, 1);
        }
       
$aGMTTime['tm_fyear'] = $aGMTTime['tm_year'] + 1900;
        return
$aGMTTime;
    }
// End [IF] return associative array?
} // End [FUNCTION] gmttime
?>

bens_nospam at benjamindsmith dot com (31-Mar-2002 02:29)

You must keep in mind the difference between your server's time and your client's time!

I ran into this one when I wrote a calendar-based reminder system with SMS messaging - guys back east were always getting their messages late. (!?!)

I wrote two functions as wrappers for date handling, ServerTime() and ClientTime() that take client time (integer timestamp) and translate to server time and vice-versa based on config file settings.

Needless to say, you CANNOT FORGET THIS.

test at test dot de (22-Aug-2001 06:05)

to set up berlin time it could look like this:

<?php
   
print "<HTML><body><pre>";
   
   
setlocale( "LC_ALL", "de_DE" );
   
   
putenv( "PHP_TZ=Europe/Berlin" );
   
   
$now = time();
   
   
print_r( localtime(time(),true) );
   
print_r( getdate() );
   
    print
date("H:i:s");
    print
date("T");
   
?>

verdy_p at wanadoo dot fr (22-Jul-2001 01:23)

The corresponding function call to get the GMT time is not specified here. Only local time is reported, according to the current TZ environment setting.
One could try to use putenv() to set another timezone temporarily, however when running PHP in safe mode, putenv() is disabled and cannot be used in scripts.
However it's possible to simulate gmttime() by using localtime() and by transforming the results in the returned array.
The biggest problem with this function is that it is using an OS-dependent and localtime() function which is also depending on the standard C library implementation (some of them, do not support accurate locales). The second problem is that localtime() does not return an index specifying the local timezone offset, so transforming this date to UTC will become very ugly. Some systems support the gmtime() C function call, some don't. To get the timezone, some C libraries provide a global _timezone variable, some provide it as a macro that use a function call, some do not provide any variable, and one must deduce it by interpreting the TZ environment. This is too much ugly for PHP.

PHP should be extended by adding support to gmttime() with the same parameters, but the returned array should include additional indices to store the timezone offsets in seconds and names for both standard time and DST, for example:
 [tz_offset_std] = 3600,
 [tz_offset_dst]= 7200,
 [tz_name_std] = 'CET', (GMT+01:00)
 [tz_name_dst] = 'CEDT'. (GMT+02:00)
Or for the international, locale-independant, Zulu time (also known as UCT or simply UT), returned by gmtime():
 [tz_offset] = 0,
 [tz_offset_dst]= 0,
 [tz_name] = 'Z',
 [tz_name_dst] = 'Z'.

But it's much easier to use PHP's date() and gmdate() to make such transformations.

Beware of DST rules! In the southern hemisphere, standard time still occurs during winter, but the southern Winter is in June, not in December ! Use the tm_isdst indicator to know which timezone to display or interpret !