localtime

(PHP 4, PHP 5)

localtime — Возвращает системное время

Описание

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

Функция localtime() возвращает массив, аналогичный структуре, возвращаемой соответствующей функцией C. Первым аргументом функции localtime() является метка времени, если этот аргумент не передан, используется текущее время, полученное вызовом функции time(). Если аргумент is_associative не передан или или равен 0, возврачается массив с числовыми индексами. Если этот аргумент равен 1, функция localtime() возврашает ассоциативный массив, содержащий компоненты структуры, возвращаемой функцией C localtime. Список индексов :

  • "tm_sec" - секунды
  • "tm_min" - минуты
  • "tm_hour" - часы
  • "tm_mday" - день месяца
  • "tm_mon" - месяц года, 0 соответствует январю
  • "tm_year" - Количество лет, прошедших с 1900 г.
  • "tm_wday" - день недели
  • "tm_yday" - порядковый номер дня в году
  • "tm_isdst" - признак летнего времени

Коментарии

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 !
2001-07-22 08:23:50
http://php5.kiev.ua/manual/ru/function.localtime.html
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_rlocaltime(time(),true) );
   
print_rgetdate() );
   
    print 
date("H:i:s");
    print 
date("T");
   
?>
2001-08-22 01:05:08
http://php5.kiev.ua/manual/ru/function.localtime.html
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.
2002-03-30 20:29:51
http://php5.kiev.ua/manual/ru/function.localtime.html
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(111111970$aNow[8]) - mktime(111111970$aNow[8]);

    if (!
$bAssoc) {
        if (
$dTimestamp == '') {
            return 
localtime(time() - $iDelta0);
        } else {
            return 
localtime($dTimestamp $iDelta0);
        }
    } else {
       
// For associative array, add full year index
       
if ($dTimestamp == '') {
           
$aGMTTime localtime(time() - $iDelta1);
        } else {
           
$aGMTTime localtime($dTimestamp $iDelta1);
        }
       
$aGMTTime['tm_fyear'] = $aGMTTime['tm_year'] + 1900;
        return 
$aGMTTime;
    } 
// End [IF] return associative array?
// End [FUNCTION] gmttime
?>
2002-04-26 03:42:37
http://php5.kiev.ua/manual/ru/function.localtime.html
You can implement gmtime quote simply.

<?php
function GetTZOffset() { 
 
$Offset date("O"0);
   
 
$Parity $Offset ? -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);
?>
2002-12-09 15:25:44
http://php5.kiev.ua/manual/ru/function.localtime.html
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);
        if( 
$tarr["tm_wday"] == )
            {
           
// found Sunday, now make the week's strings
           
for($jj 0$jj 7$jj++)
                {
               
$tarr localtime$t + ($jj $ii) * 86400);
               
$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;
    }
?>
2004-02-24 12:35:47
http://php5.kiev.ua/manual/ru/function.localtime.html
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);
}
?>
2006-12-08 14:22:31
http://php5.kiev.ua/manual/ru/function.localtime.html
Автор:
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()
2011-05-25 11:26:40
http://php5.kiev.ua/manual/ru/function.localtime.html
Автор:
its something strange on locatime function, if i test this function with zero parameter

print_r(localtime(0));

it returns this 
Array
(
    [0] => 0
    [1] => 0
    [2] => 1   <-----
    [3] => 1
    [4] => 0
    [5] => 70
    [6] => 4
    [7] => 0
    [8] => 0
)
that is not the unix epoc but one hour after, it should be
Array
(
    [0] => 0
    [1] => 0
    [2] => 0   <-----
    [3] => 1
    [4] => 0
    [5] => 70
    [6] => 4
    [7] => 0
    [8] => 0
)
2014-09-18 11:01:43
http://php5.kiev.ua/manual/ru/function.localtime.html

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