PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

gettimeofday> <date
Last updated: Fri, 09 May 2008

view this page in

getdate

(PHP 4, PHP 5)

getdate — Возвращает информацию о дате/времени

Описание

array getdate ([ int $timestamp ] )

Возвращает ассоциативный массив, содержащий информацию о дате, представленной меткой времени timestamp или текущем системном времени, если timestamp не передан. Массив содержит следующие элементы:

Индексы возвращаемого ассоциативного массива
Индекс Описание Пример значения
"seconds" Секунды От 0 до 59
"minutes" Минуты От 0 до 59
"hours" Часы От 0 до 23
"mday" Порядковый номер дня месяца От 1 до 31
"wday" Порядковый номер дня От 0 (воскресенье) до 6 (суббота)
"mon" Порядковый номер месяца От 1 до 12
"year" Порядковый номер года, 4 цифры Примеры: 1999, 2003
"yday" Порядковый номер дня в году (нумерация с 0) От 0 до 365
"weekday" Полное наименование дня недели От Sunday до Saturday
"month" Полное наименование месяца, например January или March от January до December
0 Колическтво секунд, прошедших с начала Эпохи Unix (The Unix Epoch), подобно значению, возвращаемому функцией time() и используемому функцией date(). Платформо-зависимое, в большинстве случаев от -2147483648 до 2147483647.

Пример #1 Пример использования функции getdate()

<?php
$today 
getdate(); 
print_r($today);
?>

Вывод будет выглядеть так:

Array
(
    [seconds] => 40
    [minutes] => 58
    [hours]   => 21
    [mday]    => 17
    [wday]    => 2
    [mon]     => 6
    [year]    => 2003
    [yday]    => 167
    [weekday] => Tuesday
    [month]   => June
    [0]       => 1055901520
)

See also date(), time(), and setlocale().



gettimeofday> <date
Last updated: Fri, 09 May 2008
 
add a note add a note User Contributed Notes
getdate
Anonymous
04-Apr-2008 08:38
John Sherwood says:
or you could use

mysql_select("SELECT UNIX_TIMESTAMP(fieldname) FROM tablename"), which would give you the date in seconds since unix epoch, and which you could compare to time().

However the datetime on the database server may not exactly match the datetime on the machine executing the PHP script.

Maybe better to get both at the same time - eg:
mysql_select("SELECT UNIX_TIMESTAMP(fieldname) AS `a`, UNIX_TIMESTAMP() AS `b` FROM tablename")
Chris
26-Mar-2008 09:54
This function by John Sherwood does the opposite:

function pastdate($t)
{
   if (strtotime($t) < time())
      return false;
   return true;
}
When the current time has passed $t it ought to be true.

The correct answer can be given by this simple 1-liner:
function pastdate($t)
{
  return (strtotime($t) < time());
}
timforte at gmail dot com
10-Jan-2008 08:07
It's worth noting that this is local time, not UTC/GMT - gmgetdate doesn't exist :(.

The most logical way to handle date arithmetic without hitting DST problems is to work in UTC...

function add_days($my_date,$numdays) {
  $date_t = strtotime($my_date.' UTC');
  return gmdate('Y-m-d',$date_t + ($numdays*86400));
}

[it's even faster if you use gmmktime instead of strtotime]
Nick Reale
12-Apr-2007 08:15
Anyone Interested in Generating dates for week, last week, month, last month, quarter, last quarter, YTD, Last YTD, Last Year can use this simple code.

It defaults to the date format YYYY-MM-DD but you can adjust it in the script.

<?

    $t=getdate();
   
    $today=date('Y-m-d',$t[0]);
   
    //This Week//
    $start=$t[0]-(86400*$t[wday]);
    $twstart=date('Y-m-d',$start);
   
    //Last Week//
    $lwstart=$start-604800;
    $lwend=$lwstart+518400;
    $lwstart=date('Y-m-d',$lwstart);
    $lwend=date('Y-m-d',$lwend);
   
    //This Month//
    $tmstart="$t[year]-$t[mon]-01";
   
    //Last Month//
    if($t[mon]=="1"){
    $lmstart="2007-12-01";
    }
    else {
    $lmstart="$t[year]-".($t[mon]-1)."-01";
    }
    $lmmonth=($t[mon]-1);
    if($lmmonth=="4" OR $lmmonth=="5" OR $lmmonth=="9" OR $lmmonth=="11"){
    $lmend="$t[year]-$lmmonth-30";
    }
    elseif($t[mon]=="2"){
    $lmend="$t[year]-$lmmonth-28";
    }
    else {
    $lmend="$t[year]-$lmmonth-31";
    }
   
    //This Quarter//
    if($t[mon]=="1" OR $t[mon]=="2" OR $t[mon]=="3"){
    $tqstart="$t[year]-01-01";
    $tqend="$t[year]-03-31";
    }
    elseif($t[mon]=="4" OR $t[mon]=="5" OR $t[mon]=="6"){
    $tqstart="$t[year]-04-01";
    $tqend="$t[year]-06-30";
    }
    elseif($t[mon]=="7" OR $t[mon]=="8" OR $t[mon]=="9"){
    $tqstart="$t[year]-07-01";
    $tqend="$t[year]-09-30";
    }
    else {
    $tqstart="$t[year]-10-01";
    $tqend="$t[year]-12-31";
    }
   
    //Last Quarter//
   
    if($t[mon]=="1" OR $t[mon]=="2" OR $t[mon]=="3"){
    $lwstart=($t[year]-1)."-10-01";
    $lwend=($t[year]-1)."-12-31";
    }
    elseif($t[mon]=="4" OR $t[mon]=="5" OR $t[mon]=="6") {
    $lqstart="$t[year]-01-01";
    $lqend="$t[year]-03-31";
    }
    elseif($t[mon]=="7" OR $t[mon]=="8" OR $t[mon]=="9"){
    $lqstart="$t[year]-04-01";
    $lqend="$t[year]-06-30";
    }
    else {
    $lqstart="$t[year]-07-01";
    $lqend="$t[year]-09-30";
    }
   
    //Year To Date//
    $ystart="$t[year]-01-01";
   
    //Last Year To Same Date//
    $lystart=($t[year]-1)."-01-01";
    $lytend=($t[0]-31536000);
    $lytend=date('Y-m-d',$lytend);
   
    //Last Year//
    $lyend=($t[year]-1)."-12-31";
   
   
   
    echo "This Week<br>Start $twstart<br>Finish $today<br><br>";
    echo "Last Week<br>Start $lwstart<br>Finish $lwend<br><br>";
    echo "This Month<br>Start $tmstart<br>Finish $today<br><br>";
    echo "Last Month<br>Start $lmstart<br>Finish $lmend<br><br>";
    echo "This Quarter<br>Start $tqstart<br>Finish $today<br><br>";
    echo "Last Quarter<br>Start $lqstart<br>Finish $lqend<br><br>";
    echo "Year To Date<br>Start $ystart<br>Finish $today<br><br>";
    echo "Last Year To Date<br>Start $lystart<br>Finish $lytend<br><br>";
    echo "Last Year<br>Start $lystart<br>Finish $lyend<br><br>";

?>
andre at anlex dot co dot za
13-Dec-2006 04:38
I thought best to show a posseble way to go about bypassing the end month issue where the first day in a new month will have the monday of the week that it falls in - in the old month. Use the numbering of days as the constant and work you way from there.

Example:
<?php
//-----------------------------
$now = time();
$num = date("w");
if (
$num == 0)
{
$sub = 6; }
else {
$sub = ($num-1); }
$WeekMon  = mktime(0, 0, 0, date("m", $now)  , date("d", $now)-$sub, date("Y", $now));    //monday week begin calculation
$todayh = getdate($WeekMon); //monday week begin reconvert

$d = $todayh[mday];
$m = $todayh[mon];
$y = $todayh[year];
echo
"$d-$m-$y"; //getdate converted day

?>

Allot less code makes everyone happy..
Jared Armstrong
09-Dec-2006 10:05
A nice little function I wrote to determine what number occurrence weekday it is of the month for a given timestamp. (I.e. 2nd Friday, or the 3rd Thursday)

Eg: print_r(getWeekdayOccurrence(mktime(0, 0, 0, 12, 1, 2006)));
Outputs: Array ( [0] => 1 [1] => Friday )  [The first friday]

Eg. print_r(getWeekdayOccurrence(mktime(0, 0, 0, 8, 17, 2009)));
Outputs: Array ( [0] => 3 [1] => Monday ) [The third Monday]

function getWeekdayOccurrence($time) {
    $month = intval(date("m", $time)); $day = intval(date("d", $time));
    for ($i = 0; $i < 7; $i++) {
        $days[] = date("l", mktime(0, 0, 0, $month, ($i+1), date("Y", $time)));   
    }

    $posd  = array_search(date("l", $time), $days);
    $posdm = array_search($days[0], $days) - $posd; /

    return array((($day+$posdm+6)/7), $days[$posd]);       
}
cesar at nixar dot org
22-Oct-2006 08:49
<?php

 
/**
   *  This function is similar to getdate() but it returns
   * the month information.
   *
   *  Returns an associative array containing the month
   * information of the parameters, or the current month
   * if no parameters are given.
   *
   */

 
function getmonth ($month = null, $year = null)
  {
     
// The current month is used if none is supplied.
     
if (is_null($month))
         
$month = date('n');

     
// The current year is used if none is supplied.
     
if (is_null($year))
         
$year = date('Y');

     
// Verifying if the month exist
     
if (!checkdate($month, 1, $year))
          return
null;

     
// Calculating the days of the month
     
$first_of_month = mktime(0, 0, 0, $month, 1, $year);
     
$days_in_month = date('t', $first_of_month);
     
$last_of_month = mktime(0, 0, 0, $month, $days_in_month, $year);

     
$m = array();
     
$m['first_mday'] = 1;
     
$m['first_wday'] = date('w', $first_of_month);
     
$m['first_weekday'] = strftime('%A', $first_of_month);
     
$m['first_yday'] = date('z', $first_of_month);
     
$m['first_week'] = date('W', $first_of_month);
     
$m['last_mday'] = $days_in_month;
     
$m['last_wday'] = date('w', $last_of_month);
     
$m['last_weekday'] = strftime('%A', $last_of_month);
     
$m['last_yday'] = date('z', $last_of_month);
     
$m['last_week'] = date('W', $last_of_month);
     
$m['mon'] = $month;
     
$m['month'] = strftime('%B', $first_of_month);
     
$m['year'] = $year;

      return
$m;
  }

 
// Output
 
print_r(getmonth(11, 1978));
 
print_r(getmonth());

?>
John Sherwood
14-May-2006 11:10
In response to the "Simple routine for determining whether a date in mySQL format has gone past":

function pastdate($t)
{
   if (strtotime($t) < time())
      return false;
   return true;
}

or you could use

mysql_select("SELECT UNIX_TIMESTAMP(fieldname) FROM tablename"), which would give you the date in seconds since unix epoch, and which you could compare to time().
Cas_AT_NUY_DOT_INFO
04-Mar-2006 05:47
// This functions calculates the next date only using business days
// 2 parameters, the startdate and the number of businessdays to add
    function calcduedate($datecalc,$duedays) {
    $i = 1;
    while ($i <= $duedays) {
        $datecalc += 86400; // Add a day.
        $date_info  = getdate( $datecalc );
        if (($date_info["wday"] == 0) or ($date_info["wday"] == 6) )  {
            $datecalc += 86400; // Add a day.
            continue;
        }
        $i++;
    }
    return $datecalc ;
    }
leo25in at yahoo dot com
11-May-2005 05:17
getting weekday(actual date) from any give date.

function cal_date($wday,$tstamp)
{
    return $tstamp-($wday*(24*3600));
}

function getweekday($m,$d,$y)
{
    $tstamp=mktime(0,0,0,$m,$d,$y);
   
    $Tdate = getdate($tstamp);
   
    $wday=$Tdate["wday"];
   
    switch($wday)
    {
        case 0;
        $wstamp=cal_date($wday,$tstamp);
        //echo date("Y-m-d",$wstamp);
        break;
       
        case 1;
        $wstamp=cal_date($wday,$tstamp);
        //echo date("Y-m-d",$wstamp);
        break;
       
       
        case 2;
        $wstamp=cal_date($wday,$tstamp);
        //echo date("Y-m-d",$wstamp);
        break;
       
        case 3;
        $wstamp=cal_date($wday,$tstamp);
        //echo date("Y-m-d",$wstamp);
        break;
       
        case 4;
        $wstamp=cal_date($wday,$tstamp);
        //echo date("Y-m-d",$wstamp);
        break;
       
        case 5;
        $wstamp=cal_date($wday,$tstamp);
        //echo date("Y-m-d",$wstamp);
        break;
       
        case 6;
        $wstamp=cal_date($wday,$tstamp);
        //echo date("Y-m-d",$wstamp);
        break;
    }
   
   
     $w["day"]=date("d",$wstamp);
     $w["month"]=date("m",$wstamp);
     $w["year"]=date("Y",$wstamp);
    
     return $w;

}
Liis make
16-Sep-2004 03:22
function win2unix($date_string,$date_timestamp)
{

   $epoch_diff = 11644473600; // difference 1601<>1970 in seconds. see reference URL
   $date_timestamp = $date_timestamp * 0.0000001;
   $unix_timestamp = $date_timestamp - $epoch_diff;
   echo date($date_string,$unix_timestamp);   
}
getisomonday($year, $week)
21-Apr-2004 02:58
getdate does not convert week numbers. this function relies on strftime to find a timestamp that falls on the monday of specified year and ISO week:

<?php function getisomonday($year, $week) {
       
# check input
       
$year = min ($year, 2038); $year = max ($year, 1970);
       
$week = min ($week, 53); $week = max ($week, 1);
       
# make a guess
       
$monday = mktime (1,1,1,1,7*$week,$year);
       
# count down to week
       
while (strftime('%V', $monday) != $week)
               
$monday -= 60*60*24*7;
       
# count down to monday
       
while (strftime('%u', $monday) != 1)
               
$monday -= 60*60*24;
       
# got it
       
return $monday;
}
?>
Yura Pylypenko (plyrvt at mail dot ru)
15-Sep-2003 06:29
In addition to canby23 at ms19 post:
It's a very bad idea to consider day having 24 hours (86400 secs), because some days have 23, some - 25 hours due to daylight saving changes. Using of mkdate() and strtotime() is always preferred. strtotime() also has a very nice behaviour of datetime manipulations:
<?php
echo strtotime ("+1 day"), "\n";
echo
strtotime ("+1 week"), "\n";
echo
strtotime ("+1 week 2 days 4 hours 2 seconds"), "\n";
echo
strtotime ("next Thursday"), "\n";
echo
strtotime ("last Monday"), "\n";
?>
intronis
11-Sep-2003 11:04
When adding a timestamp to a database from php, be carefule because if your DB Server is a different computer than your webserver, the NOW() function in the SQL will use the DB Server's time, and not the web server's. You can use NTP to synch the times on both computers.
logan dot hall at asu dot edu
11-Mar-2002 12:32
It seems that 'yday' (the day of the year) that php produces is one less than what the unix 'date +%j' produces.

Not sure why this is, but I would guess that php uses 0-365 rather than 1-366 like unix does.  Just something to be careful of.
ih2 at morton-fraser dot com
17-Oct-2000 05:01
To do comparisons on dates stored in mysql db against 7 days ago, 1 month ago etc use the following:
$last_week = date("Y-m-d", mktime(0,0,0, date(m), date(d)-7,date(Y)));

if($date > $last_week)
    {
     etc.
This allows for intelligent looping i.e. works at start/end of month/year
I have noticed other postings re this and they have not worked for me.Hope this helps.

gettimeofday> <date
Last updated: Fri, 09 May 2008
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites