PHP Doku:: Gibt Datums- und Zeitinformationen zurück - function.getdate.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzDatums- und zeitrelevante ErweiterungenDatum und UhrzeitDatum/Uhrzeit Funktionengetdate

Ein Service von Reinhard Neidl - Webprogrammierung.

Datum/Uhrzeit Funktionen

<<date

gettimeofday>>

getdate

(PHP 4, PHP 5)

getdateGibt Datums- und Zeitinformationen zurück

Beschreibung

array getdate ([ int $timestamp = time() ] )

Gibt ein assoziatives array mit Datums- und Zeitangaben des angegebenen timestamp zurück. Ist kein Timestamp angegeben, wird die lokal gültige Zeit verwendet.

Parameter-Liste

timestamp

Der optionale Parameter timestamp ist ein Unix Timestamp als integer oder die aktuelle lokale Zeit wenn kein timestamp übergeben wurde. Er entspricht dann also dem Ergebnis der Funktion time().

Rückgabewerte

Gibt ein assoziatives Array mit Informationen zum timestamp zurück. Die Elemente des zurückgegebenen assoziativen Arrays sind folgende:

Schlüsselelemente des zurückgegebenen assoziativen Arrays
Key Beschreibung Beispiel für Rückgabewerte
"seconds" Numerische Repräsentation der Sekunden zwischen 0 und 59
"minutes" Numerische Repräsentation der Minuten zwischen 0 und 59
"hours" Numerische Repräsentation der Stunden zwischen 0 und 23
"mday" Numerische Repräsentation des Monatstags zwischen 1 und 31
"wday" Numerische Repräsentation des Wochentags zwischen 0 (für Sonntag) und 6 (für Sonnabend)
"mon" Numerische Repräsentation des Monats zwischen 1 und 12
"year" Eine vollständige numerische Repräsentation der Jahreszahl (vierstellig) Beispiele: 1999 oder 2003
"yday" Numerische Repräsentation des Tages des Jahres zwischen 0 und 365
"weekday" Eine vollständige textuelle Repräsentation des Wochentags zwischen Sonntag und Sonnabend
"month" Eine vollständige textuelle Repräsentation des Monatsnamens, wie Januar oder März zwischenJanuar und Dezember
0 Sekunden seit der Unix Epoche, ähnlich den Werten, die von der Funktion time() zurückgegeben und von der Funktion date() verwendet werden. Abhängig vom System, typischerweise ein Wert zwischen -2147483648 und 2147483647.

Beispiele

Beispiel #1 getdate()-Beispiel

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

Das oben gezeigte Beispiel erzeugt eine ähnliche Ausgabe wie:

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

Siehe auch

  • date() - Formatiert ein(e) angegebene(s) Ortszeit/Datum
  • idate() - Format a local time/date as integer
  • time() - Gibt den aktuellen Unix-Timestamp/Zeitstempel zurück
  • setlocale() - Setzt Locale Informationen


13 BenutzerBeiträge:
- Beiträge aktualisieren...
moshe at unirgy dot com
8.09.2009 1:47
A function/method to calculate the next workday, taking into account US federal holidays:
<?php
function getNextWorkDayTime($date=null)
{
   
$time = is_string($date) ? strtotime($date) : (is_int($date) ? $date : time());
   
$y = date('Y', $time);
   
// calculate federal holidays
   
$holidays = array();
   
// month/day (jan 1st). iteration/wday/month (3rd monday in january)
   
$hdata = array('1/1'/*newyr*/, '7/4'/*jul4*/, '11/11'/*vet*/, '12/25'/*xmas*/, '3/1/1'/*mlk*/, '3/1/2'/*pres*/, '5/1/5'/*memo*/, '1/1/9'/*labor*/, '2/1/10'/*col*/, '4/4/11'/*thanks*/);
    foreach (
$hdata as $h1) {
       
$h = explode('/', $h1);
        if (
sizeof($h)==2) { // by date
           
$htime = mktime(0, 0, 0, $h[0], $h[1], $y); // time of holiday
           
$w = date('w', $htime); // get weekday of holiday
           
$htime += $w==0 ? 86400 : ($w==6 ? -86400 : 0); // if weekend, adjust
       
} else { // by weekday
           
$htime = mktime(0, 0, 0, $h[2], 1, $y); // get 1st day of month
           
$w = date('w', $htime); // weekday of first day of month
           
$d = 1+($h[1]-$w+7)%7; // get to the 1st weekday
           
for ($t=$htime, $i=1; $i<=$h[0]; $i++, $d+=7) { // iterate to nth weekday
                
$t = mktime(0, 0, 0, $h[2], $d, $y); // get next weekday
                
if (date('n', $t)>$h[2]) break; // check that it's still in the same month
                
$htime = $t; // valid
           
}
        }
       
$holidays[] = $htime; // save the holiday
   
}
    for (
$i=0; $i<5; $i++, $time+=86400) { // 5 days should be enough to get to workday
       
if (in_array(date('w', $time), array(0, 6))) continue; // skip weekends
       
foreach ($holidays as $h) { // iterate through holidays
           
if ($time>=$h && $time<$h+86400) continue 2; // skip holidays
       
}
        break;
// found the workday
   
}
    return
$time;
}
?>


[EDIT BY danbrown AT php DOT net: Contains a bugfix by (yhbeh888 AT yahoo DOT com) on 24-FEB-2010 to address a bug in the "7th line counted from the bottom."]
binupillai2003 at yahoo dot com(Binu V Pillai)
25.08.2009 9:32
<?php
/* Function to find the first and last day of the month from the given date.
*
* Author Binu v Pillai            binupillai2003@yahoo.com
* @Param            String             yyyy-mm-dd
*
*/
function findFirstAndLastDay($anyDate)
{
   
//$anyDate            =    '2009-08-25';    // date format should be yyyy-mm-dd
   
list($yr,$mn,$dt)    =    split('-',$anyDate);    // separate year, month and date
   
$timeStamp            =    mktime(0,0,0,$mn,1,$yr);    //Create time stamp of the first day from the give date.
   
$firstDay            =     date('D',$timeStamp);    //get first day of the given month
   
list($y,$m,$t)        =     split('-',date('Y-m-t',$timeStamp)); //Find the last date of the month and separating it
   
$lastDayTimeStamp    =    mktime(0,0,0,$m,$t,$y);//create time stamp of the last date of the give month
   
$lastDay            =    date('D',$lastDayTimeStamp);// Find last day of the month
   
$arrDay                =    array("$firstDay","$lastDay"); // return the result in an array format.
   
   
return $arrDay;
}

//Usage
$dayArray=array();
$dayArray=findFirstAndLastDay('2009-02-25');
print
$dayArray[0];
print
$dayArray[1];
?>
eric dot schultz at NOSPAM dot CyVon dot com
17.12.2008 3:33
Here is another gmgetdate that is a little faster/suscint (no loops).

<?php
function gmgetdate2($ts = null){
       
$k = array('seconds','minutes','hours','mday',
               
'wday','mon','year','yday','weekday','month',0);
        return(
array_combine($k,split(":",
               
gmdate('s:i:G:j:w:n:Y:z:l:F:U',is_null($ts)?time():$ts))));
        }
?>

It also returns the values in the same order as getdate.
Anonymous
16.10.2008 16:01
I couldn't get the last 2 examples of gmgetdate() to work, so here's a modification that did work for me that behaves exactly like getdate() :

<?php
function gmgetdate($timestamp = null) {
    if (
is_null($timestamp)) { $timestamp = time(); }

   
$dateParts = array(
       
'mday'    => 'j',
       
'wday'    => 'w',
       
'yday'    => 'z',
       
'mon'     => 'n',
       
'year'    => 'Y',
       
'hours'   => 'G',
       
'minutes' => 'i',
       
'seconds' => 's',
       
'weekday' => 'l',
       
'month'   => 'F',
       
0         => 'U'
   
);

    while (list(
$part, $format) = each($dateParts)) {
       
$GMdateParts[$part] = gmdate($format, $timestamp);
    }

    return
$GMdateParts;
}
?>
chris AT cmbuckley DOT co DOT uk
8.08.2008 16:08
For those who want the gmgetdate function that matches the behaviour of getdate:

<?php
function gmgetdate($timestamp = null) {
    if (
is_null($timestamp)) { $timestamp = time(); }

   
$dateParts = array(
       
'mday'    => 'j',
       
'wday'    => 'w',
       
'yday'    => 'z',
       
'mon'     => 'n',
       
'year'    => 'Y',
       
'hours'   => 'G',
       
'minutes' => 'i',
       
'seconds' => 's',
       
'weekday' => 'l',
       
'month'   => 'F',
       
0         => 'U'
   
);

    while (list(,
$value) = each($dateParts)) {
       
$value = gmdate($value, $timestamp);
        if (
is_numeric($value)) { $value = (int)$value; }
    }

    return
$dateParts;
}
?>
timforte at gmail dot com
10.01.2008 17: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...

<?php
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]
andre at anlex dot co dot za
13.12.2006 13: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
10.12.2006 7: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]

<?php
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.10.2006 17: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());

?>
Cas_AT_NUY_DOT_INFO
4.03.2006 14:47
<?php
// 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.05.2005 14:17
getting weekday(actual date) from any give date.

<?php
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;

}
?>
getisomonday($year, $week)
21.04.2004 23: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.09.2003 15: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";
?>



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)