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

search for in the

getdate> <date_timezone_set
Last updated: Fri, 27 Jun 2008

view this page in

date

(PHP 4, PHP 5)

date — Formatează data/timpul local

Descriere

string date ( string $format [, int $ timestamp ] )

Returnează un şir formatat conform cu formatul transmis ca parametru al funcţiei, utilizând întregul timestamp sau timpul local dacă nu este utilizat parametrul timestamp .

Notă: Perioada validă a timestamp este cuprinsă, de regulă, între vineri, 13 Decembrie 1901 20:45:54 GMT şi marţi, 19 ianuarie 2038 03:14:07 GMT. (Acestea sunt datele care corespund minimului, respectiv maximului unui întreg cu semn reprezentat pe 32 de biţi.)
Pentru a genera un timestamp dintr-un şir reprezentând o dată, puteţi utiliza funcţia strtotime(). De asemenea, unele sisteme de gestiune a bazelor de date au funcţii care pot converti formatul lor de dată în timestamps (cum ar fi funcţia MySQL UNIX_TIMESTAMP).

Următoarele caractere sunt recunoscute în şirul format :

  • a - "am" sau "pm"
  • A - "AM" sau "PM"
  • B - timpul Swatch Internet
  • d - ziua din lună, 2 cifre cu zero iniţial; de exemplu "01" to "31"
  • D - ziua din săptămână, în engleză, textual, 3 litere; de exemplu "Fri"
  • F - month, textual, long; de exemplu "January"
  • g - ora, format de 12 ore, fără zero iniţial; de exemplu "1" până la "12"
  • G - ora, format de 24 de ore, fără zero iniţial; de exemplu "0" până la "23"
  • h - ora, format 12 ore, cu zero iniţial; de exemplu "01" până la "12"
  • H - ora, format 24 de ore, cu zero iniţial; de exemplu "00" până la "23"
  • i - minute, cu zero iniţial; de exemplu "00" până la "59"
  • I (litera i majusculă) - "1" ora de vară, "0" în caz contrar.
  • j - ziua din lună, fără zero iniţial; de exemplu "1" până la "31"
  • l (litera 'L' minusculă) - ziua din săptămână, textual, în engleză, scurt; de exemplu "Friday"
  • L - valoare booleană pentru anii bisecţi; de exemplu "0" dacă nu e an bisect sau "1" dacă este an bisect
  • m - luna, cu zero iniţial; de exemplu "01" până la "12"
  • M - luna, textual, în engleză, 3 litere; de exemplu "Jan"
  • n - luna fără zero iniţial; de exemplu "1" până la "12"
  • O - diferenţa până la ora Greenwich în ore; de exemplu "+0200"
  • r - data formatată conform recomandării RFC 822; de exemplu "Thu, 21 Dec 2000 16:01:07 +0200" (adăugată în PHP 4.0.4)
  • s - secunde; de exemplu "00" până la "59"
  • S - sufixul ordinal englezesc pentru ziua din lună, 2 caractere; de exemplu "th", "nd"
  • t - numărul de zile dintr-o lună dată; de exemplu "28" până la "31"
  • T - setările de reprezentare a timpului pe un calculator; de exemplu "MDT"
  • U - secunde de la începutul epocii UNIX
  • w - ziua din săptămână, numerică, de exemplu "0" (duminică) până la "6" (sâmbătă)
  • W - numărul săptămânii din an conform ISO-8601; săptămâna începe lunea (adăugată în PHP 4.1.0)
  • Y - anul, 4 cifre; de exemplu "1999"
  • y - anul, 2 cifre; de exemplu "99"
  • z - ziua din an; de exemplu "0" până la "365"
  • Z - diferenţa de timp faţă de UTC, în secunde (de exemplu "-43200" până la "43200"). Diferenţele pentru zonele aflate la vest de UTC sunt întotdeauna negative şi celelalte sunt întotdeauna pozitive.
Caracterele nerecunoscute din format vor fi afişate ca atare. Formatul "Z" va returna întotdeauna "0" când se foloseşte gmdate().

Example #1 Exemplu date()

echo date ("l dS of F Y h:i:s A");
echo "July 1, 2000 este într-o zi de " . date ("l", mktime(0,0,0,7,1,2000));

Puteţi preveni expandarea unui caracter de formatare precedându-l cu un backslash. Dacă astfel ia naştere un caracter escape predefinit este necesară adăugarea încă unui backslash.

Example #2 Caractere escape în funcţia date()

echo date("l \e\s\\t\e \i\\n j"); // va afişa ceva de genul 'Saturday este in 8'

Este posibil să utilizaţi funcţiile date() şi mktime() împreună pentru a găsi date în viitor sau în trecut.

Example #3 Exemplu date() şi mktime()

$miine = mktime (0,0,0,date("m")  ,date("d")+1,date("Y"));
$luna_trecuta = mktime (0,0,0,date("m")-1,date("d"),  date("Y"));
$anul_viitor = mktime (0,0,0,date("m"),  date("d"),  date("Y")+1);

Notă: Această modalitate de găsire a datelor din trecut sau viitor este mai demnă de încredere decât simpla adăugare sau scădere de secunde la un timestamp, datorită orei de vară.

Câteva exemple de formatare a datei utilizând funcţia date(). Este recomandat să faceţi escape la toate caracterele din şirul de formatare pe care nu doriţi ca funcţia să le expandeze, precum şi la cele care momentan nu au o semnificaţie, din cel puţin două motive: pot apărea rezultate neaşteptate; alte caractere pot avea o semnificaţie în versiuni viitoare ale PHP. Când faceţi escape ţineţi cont că unele caractere (n, t) capătă semnificaţii speciale. Pentru a preveni acest lucru utilizaţi apostroful pentru încadrarea şirului de formatare.

Example #4 Formatare cu funcţia date()

/* Today is March 10th, 2001, 5:16:18 pm */
$azi = date("F j, Y, g:i a");                   // March 10, 2001, 5:16 pm
$azi = date("m.d.y");                           // 03.10.01
$azi = date("j, n, Y");                         // 10, 3, 2001
$azi = date("Ymd");                             // 20010310
$azi = date('h-i-s, j-m-y, it is w Day z ');    // 05-16-17, 10-03-01, 1631 1618 6 Fripm01
$azi = date('\e\s\t\e \z\i\u\a \d\e j.');       // este ziua de 10.
$azi = date("D M j G:i:s T Y");                 // Sat Mar 10 15:16:08 MST 2001
$azi = date('H:m:s \l \e\s\t\e \l\u\n\a');      // 17:03:17 l este luna
$azi = date("H:i:s");                           // 17:16:17

Pentru a formata datele în alte limbi trebuie să utilizaţi funcţiile setlocale() şi strftime().

Vezi, de asemenea, getlastmod(), gmdate(), mktime(), strftime() şi time().



getdate> <date_timezone_set
Last updated: Fri, 27 Jun 2008
 
add a note add a note User Contributed Notes
date
desisco.com.ve
03-Jul-2008 09:00
I was looking for this for a fee minutes and finally get the solution,

formating a string date;

<?php

$YourDate
="2008-06-30";    //This is your valid String Date

$NewFormatedDate=date("d",strtotime ($YourDate)); // Returns the day of the Month = 30

$NewFormatedDate=date("M",strtotime ($YourDate)); // Returns the name of the Month = Jun

?>
dmagick at gmail dot com
02-Jul-2008 07:44
Slight amendment to halocastle at yahoo dot com 's code as it doesn't take into account when a month finishes on a Saturday (eg May 2008).

$start_date = mktime(0, 0, 0,$start_month, 1, $start_year);

$days_in_month = date('t', $start_date);
$month_first_day = date('w', $start_date);

$j = $month_first_day;
$num_weeks = 1;

for($i = 1; $i <= $days_in_month; $i++) {
    $j++;
    if($j == 7) {
        $j = 0;
        $num_weeks++;
    }
}

// if the last day of the month happens to be a Saturday,
// take one off the number of weeks
// because it was being added inside the for loop.
if ($j == 0) {
    $num_weeks--;
}
halocastle at yahoo dot com
30-Jun-2008 09:20
Weeks and days for any month/year combo:

$m = 2; // February
$Y = 2008;

// constants used here for legibility, use $vars for dynamicon...
define('MONTH_DAYS',date('t', strtotime(date($m . '/01/' . $Y))));
// w:0->6 = Sun->Sat
define('MONTH_FIRST_DAY',date('w', strtotime(date($m . '/01/' . $Y))));

for($i = 1, $j = MONTH_FIRST_DAY, $w = 1;$i <= MONTH_DAYS;$i++) {
  $week[$w][$j] = $i;
  $j++;
  if($j == 7) {
    $j = 0;
    $w++;
  }
}

print_r($week):
-----------------------
Array
(
    [1] => Array
        (
            [5] => 1
            [6] => 2
        )

    [2] => Array
        (
            [0] => 3
            [1] => 4
            [2] => 5
            [3] => 6
            [4] => 7
            [5] => 8
            [6] => 9
        )

    [3] => Array
        (
            [0] => 10
            [1] => 11
            [2] => 12
            [3] => 13
            [4] => 14
            [5] => 15
            [6] => 16
        )

    [4] => Array
        (
            [0] => 17
            [1] => 18
            [2] => 19
            [3] => 20
            [4] => 21
            [5] => 22
            [6] => 23
        )

    [5] => Array
        (
            [0] => 24
            [1] => 25
            [2] => 26
            [3] => 27
            [4] => 28
            [5] => 29
        )

)
Kavi Siegel
29-Jun-2008 07:18
I wrote the following function to show a series of drop down boxes to select the date. When provided with a timestamp, that date is selected by default, when none is provided, the current date is selected.

function chooseDate($timestamp = ""){
    if($timestamp == ""){
        $timestamp = time();
    }
    $months = array(null, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
    unset($months[0]);
    print_r($months);
    $out = '<select name="month">';
    foreach($months as $key => $month){
        if($month == date('M', $timestamp)){
            $out .= '<option value="'.$key.'" selected="selected">'.$month.'</option>';
        }else{
            $out .= '<option value="'.$key.'">'.$month.'</option>';
        }
    }
    $out .= '</select><select name="days">';
    for($i = 1; $i <= 32; $i++){
        if($i == date('j', $timestamp)){
            $out .= '<option value="'.$i.'" selected="selected">'.$i.'</option>';
        }else{
            $out .= '<option value="'.$i.'">'.$i.'</option>';
        }
    }
    $out .= "</select><select name='year'>";
    for($i = date('Y'); $i >= 1970; $i--){
        if($i == date('Y', $timestamp)){
            $out .= '<option value="'.$i.'" selected="selected">'.$i.'</option>';
        }else{
            $out .= '<option value="'.$i.'">'.$i.'</option>';
        }
    }
    $out .= "</select>";
    return $out;
}

Usage is simple:

echo chooseDate(); // Will select current date
echo chooseDate(1149566400); // Will select June 6th, 2006
aplarsen
26-Jun-2008 01:12
@anonymous (12-Jun-2008 08:45):
date("t") returns the last day of the month, not the last working day of the month.

A cleaner example would be as follows:
<?php
function lastworkingday($date)
{   
   for(
$lastday=mktime(0,0,0,date("m",$date),
      
date("t",$date),date("Y",$date));
    
date("w",$lastday)==0 || date("w",$lastday)==6;
    
$lastday-=60*60*24);
   return
date("j",$lastday);
}
?>
kontakt at arthur minus schiwon dot de
18-Jun-2008 03:29
to get the week of the month simply use:
ceil( date("j") / 7 );
Anonymous
12-Jun-2008 08:45
Alternatively use date('t',$yourDate)
diego at diego dot eng dot br
09-Jun-2008 04:27
I made a small code to get the last working day of the month:

<?php

$times
= strtotime(date("Y")."-".date("m")."-".date("t"));
for (
$lastworkingday=0;$lastworkingday==0;$times-=86400)
   if (
date("w",$times)!=0 && date("w",$times)!=6) $lastworkingday = date("j",$times);
print
$lastworkingday;

?>
phil dot taylor at enilsson dot com
25-May-2008 10:37
Found this helpful when converting unix dates for use with the ical file format.

// Converts a unix timestamp to iCal format (UTC) - if no timezone is
// specified then it presumes the uStamp is already in UTC format.
// tzone must be in decimal such as 1hr 45mins would be 1.75, behind
// times should be represented as negative decimals 10hours behind
// would be -10
       
    function unixToiCal($uStamp = 0, $tzone = 0.0) {
   
        $uStampUTC = $uStamp + ($tzone * 3600);       
        $stamp  = date("Ymd\THis\Z", $uStampUTC);
       
        return $stamp;       

    }
chubby at chicks dot com
23-May-2008 06:54
/**
     * Checks wether a date is between an interval
     *
     * Usage:
     *     
     * // check if today is older than 2008/12/31
     * var_dump(currentDayIsInInterval('2008/12/31'));
     * // check if today is younger than 2008/12/31
     * var_dump(currentDayIsInInterval(null,'2008/12/31'));
     * // check if today is between 2008/12/01 and 2008/12/31
     * var_dump(currentDayIsInInterval('2008/12/01','2008/12/31')); 
     *
     * Will trigger errors if date is in wrong format, notices if $begin > $end    
     *         
     * @param string $begin Date string as YYYY/mm/dd
     * @param string $end Date string as YYYY/mm/dd
     * @return bool 
     */
function currentDayIsInInterval($begin = '',$end = '')
{
        $preg_exp = '"[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]"';
        $preg_error = 'Wrong parameter passed to function '.__FUNCTION__.' : Invalide date
format. Please use YYYY/mm/dd.';
        $interval_error = 'First parameter in '.__FUNCTION__.' should be smaller than
second.';
        if(empty($begin))
        {
                $begin = 0;
        }
        else
        {
                if(preg_match($preg_exp,$begin))
                {
                        $begin = (int)str_replace('/','',$begin);
                }
                else
                {
                        trigger_error($preg_error,E_USER_ERROR);
                }
        }
        if(empty($end))
        {
                $end = 99999999;
        }
        else
        {
                if(preg_match($preg_exp,$end))
                {
                        $end = (int)str_replace('/','',$end);
                }
                else
                {
                        trigger_error($preg_error,E_USER_ERROR);
                }
        }
        if($end < $begin)
        {
                trigger_error($interval_error,E_USER_WARNING);
        }
        $time = time();
        $now = (int)(date('Y',$time).date('m',$time).date('j',$time));
        if($now > $end or $now < $begin)
        {
                return false;
        }
        return true;
}
wilson dot p dot pereira at itelefonica dot com dot br
21-May-2008 08:37
The function below extracts any date time value basead in the string format.
Returns an associative array with day,month,year,hour,min and seg separated.

function ExtractDateTimeByFormat($strDateTime, $strFormat="dmYHis")
{
 //extract the format
 $i = 0;
 $aFieldOrder = array();
 $nFields = 0;
        $strExtraction = "";
        while(isset($strFormat[$i]))
        {
            $strField = $strFormat[$i];
            switch ( strtolower($strField) )
            {
                case "D";
                case "d";
                    $aFieldOrder[$nFields] = "d";
                    $nFields++;
                    $strExtraction .= "%d";
                    if(isset($strFormat[$i+1]))
                    {
                        $strExtraction .= "%*1c";
                    }
                break;

                case "M";
                case "m";
                    $aFieldOrder[$nFields] = "m";
                    $nFields++;
                    $strExtraction .= "%d";
                    if(isset($strFormat[$i+1]))
                    {
                        $strExtraction .= "%*1c";
                    }
                break;

                case "y";
                case "Y";
                    $aFieldOrder[$nFields] = "y";
                    $nFields++;
                    $strExtraction .= "%4d";
                    if(isset($strFormat[$i+1]))
                    {
                        $strExtraction .= "%*1c";
                    }
                break;

                case "h";
                case "H";
                    $aFieldOrder[$nFields] = "h";
                    $nFields++;
                    $strExtraction .= "%d";
                    if(isset($strFormat[$i+1]))
                    {
                        $strExtraction .= "%*1c";
                    }
                break;

                case "i";
                    $aFieldOrder[$nFields] = "i";
                    $nFields++;
                    $strExtraction .= "%d";
                    if(isset($strFormat[$i+1]))
                    {
                        $strExtraction .= "%*1c";
                    }
                break;

                case "S";
                case "s";
                    $aFieldOrder[$nFields] = "s";
                    $nFields++;
                    $strExtraction .= "%d";
                    if(isset($strFormat[$i+1]))
                    {
                        $strExtraction .= "%*1c";
                    }
                break;
            }
            $i++;
        }

    $aValues = array();
    $aValues = sscanf($strDateTime,$strExtraction);

    return array_combine($aFieldOrder,$aValues);

}
wulf dot kaiser at mpimf-heidelberg dot mpg dot de
21-May-2008 01:00
For output formatting of a SAMP based seminar announcement system, i had to fetch the date of every friday of a given month in a given year. Here's what i did:

<?php

$givenYear
= $_GET["givenYear"]; # assume "2006"
$givenMonth = $_GET["givenMonth"]; # assume "12"

if ($givenMonth != '12') {

   
$nextGivenMonth = "1";
   
$nextGivenYear = $givenYear + 1;}

    else {

       
$nextGivenMonth = $givenMonth + 1;
       
$nextGivenYear = $givenYear;}
       
       
# Get the first weekday of the month

       
$firstDayOfMonth = date("d", mktime(0, 0, 0, $givenMonth, 1, $givenYear));
       
$firstWeekDayOfMonth = date("l", mktime(0, 0, 0, $givenMonth, 1, $givenYear));
       
       
# Count days to first Friday

       
switch ($firstWeekDayOfMonth) {

            case
'Monday': $numOfDaysToFirstFriday = "4"; break;
            case
'Tuesday': $numOfDaysToFirstFriday = "3"; break;
            case
'Wednesday': $numOfDaysToFirstFriday = "2"; break;
            case
'Thursday': $numOfDaysToFirstFriday = "1"; break;
            case
'Friday': $numOfDaysToFirstFriday = "0"; break;
            case
'Saturday': $numOfDaysToFirstFriday = "6"; break;
            case
'Sunday': $numOfDaysToFirstFriday = "5"; break;}
           
           
# Get first Friday's date

           
$numOfDaysToFirstFriday = 1 + $numOfDaysToFirstFriday;
           
$firstFridayOfMonthDate = date("d.m.Y", mktime(0, 0, 0, $givenMonth, $numOfDaysToFirstFriday, $givenYear));
           
$firstFridayOfMonthDay = date("d", mktime(0, 0, 0, $givenMonth, $numOfDaysToFirstFriday, $givenYear));
           
           
# Get the last weekday of the month

           
$lastDayOfMonth date("d", strtotime("-1 day", strtotime(date("$nextGivenYear-$nextGivenMonth-01"))));
           
$lastWeekDayOfMonth date("l", strtotime("-1 day", strtotime(date("$nextGivenYear-$nextGivenMonth-01"))));
           
           
# Count days to last Friday

           
switch ($lastWeekDayOfMonth) {

                case
'Monday': $numOfDaysToLastFriday = "3"; break;
                case
'Tuesday': $numOfDaysToLastFriday = "4"; break;
                case
'Wednesday': $numOfDaysToLastFriday = "5"; break;
                case
'Thursday': $numOfDaysToLastFriday = "6"; break;
                case
'Friday': $numOfDaysToLastFriday = "0"; break;
                case
'Saturday': $numOfDaysToLastFriday = "1"; break;
                case
'Sunday': $numOfDaysToLastFriday = "2"; break;}
               
               
# Get last Friday's date

               
$numOfDaysToLastFriday = $lastDayOfMonth - $numOfDaysToLastFriday;
               
$lastFridayOfMonthDate = date("d.m.Y", mktime(0, 0, 0, $givenMonth, $numOfDaysToLastFriday, $givenYear));
               
$lastFridayOfMonthDay = date("d", mktime(0, 0, 0, $givenMonth, $numOfDaysToLastFriday, $givenYear));

               
$divisor = $lastFridayOfMonthDay - $firstFridayOfMonthDay;
               
$divisor = $divisor / 7;
                global
$divisor;
               
               
# Get the dates of all Fridays in the given Month (can be either 4 or 5)

               
if ($divisor=='3') {

                   
$firstFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $numOfDaysToFirstFriday, $givenYear));
                   
$secondFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 14, $givenYear));
                   
$thirdFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 7, $givenYear));
                   
$lastFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $numOfDaysToLastFriday, $givenYear));}

                    else if (
$divisor=='4') {

                       
$firstFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $numOfDaysToFirstFriday, $givenYear));
                       
$secondFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 21, $givenYear));
                       
$thirdFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 14, $givenYear));
                       
$fourthFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 7, $givenYear));
                       
$lastFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $numOfDaysToLastFriday, $givenYear));}

?>

Comments, suggestions and bugfixes are welcome ;-))
Raymond Irving
25-Mar-2008 08:44
I have written a little Date Class Library for PHP that supports timestamps for dates greater than 2038 and lesser than 1970.

This library can be used in both PHP4 and PHP5.

Check it out here:

http://xwisdomhtml.com/dateclass.html
boyfilhote at yahoo dot com dot br
21-Mar-2008 02:29
Find out how many days a month has (including leap-years) in one single line command:

$numberOfDays = date("d", mktime(0, 0, 0, $month + 1, 0, $year));

This is possible because if you set the field "day" as ZERO in MKTIME, it will consider the last day of month-1.
ash at atomic-network dot co dot uk
20-Mar-2008 09:26
in regards to: [takzik at ebanat dot com]

simplest way of displaying / formatting dates. strtotime()

<?php
# Date: y-m-d => d-m-y
$time =explode("-","2008-01-01");
krsort($time);
print
implode("-",$time);
?>
<p>Will return: 01-01-2008.
<?php
# Date: d-m-y => y-m-d
$time =explode("-","01-01-2008");
krsort($time);
print
"<p>".implode("-",$time);
?>
<p>Will return: 2008-01-01.
<?php
# Quickest: Y-m-d => American Format
print date("m-d-Y",strtotime("2008-02-01"));
?>
<p>Will return: 02-01-2008.
<?php
# Quickest: Y-m-d => Brittish Format
print date("d.m.Y",strtotime("2008-01-01"));
?>
<p>Will return: 01.01.2008.
Anonymous
17-Mar-2008 10:56
Useful tool for creating DATE() specs without having to run 35 tests to get it right: http://www.bitbybit.dk/mysql/date_format/ (says mysql, but covers PHP as well)
Dave Schlaegel
17-Mar-2008 09:09
Here is an easy MySQL way of getting the difference in dates. For me it is more logical to do this on the select than running it though an additional PHP function after selecting the date. But depends on what your doing of course. I hope it helps.

SELECT ABS(DATEDIFF(NOW(),yourdateField)) as dateDiff
Anonymous
29-Feb-2008 01:05
## This will produce the first day of last month and the last day of last month
## 2008-01-01 2008-01-31
<?php
echo date("Y-m-01", strtotime("-1 month", strtotime(date("Y-m-d"))))." ".date("Y-m-d", strtotime("-1 day", strtotime(date("Y-m-01")))) ?>
jwagner dot DO at NOT dot SPAM dot digilog dot de
21-Feb-2008 02:06
The PHP4 replacement for ISO8601 posted by fokeyjoe has a little flaw:
The time in ISO is in 24 hour format, so an uppercase H must be used.
Correct format is:

$sISO8601=date('Y-m-d\TH:i:s',$nTimestamp). substr_replace(date('O',$nTimestamp),':',3,0);

Short version for NOW:
$sISO8601=date('Y-m-d\TH:i:s'). substr_replace(date('O'),':',3,0);
Juan Paredes
25-Jan-2008 11:59
Complementing the information by ZZigc on 28-Dec-2007 07:38, if you want to calculate the number of weeks in a given year, according to the week definition by ISO 8601, the following should be enough:

date('W', mktime(0,0,0,12,28,$year) );

(the last week on a give year always contains 28-Dec)
jc
31-Dec-2007 06:28
date("W") returns the iso8601 week number, while date("Y") returns the _current_ year. This can lead to odd results. For example today (dec 31, 2007) it returns 1 for the week and of course 2007 for the year. This is not wrong in a strict sense because iso defines this week as the first of 2008 while we still have 2007.

So, if you don't have another way to safely retrieve the year according to the iso8061 week-date - strftime("%G") doesn't work on some systems -, you should be careful when working with date("W").

For most cases strftime("%W") should be a safe replacement.

[edit: Much easier is to use "o" (lower case O) instead of "Y"]
ZZigc
28-Dec-2007 10:38
I wanted to get the number of weeks for particular year.

Example with date():
<?php

 $weeks_in_year
= date("W", strtotime("12/31/2007"));

?>

It works for years smaller than current year, but returns '01' when year was the same or bigger as current year.
Not sure if I missed something or maybe misused this function but I couldn't get it to work even with different date representations.

So the workaround was using different function.

Example with strftime():
<?php

 $weeks_in_year
= strftime("%W",strtotime("12/31/2007"));

?>

Now it works as a charm.

PHP v.4.4.7
june at overlie dot no
19-Dec-2007 06:54
re: marius at svr dot ro

to anyone using marius' function, it needs some minor fixes (look for a ---->)

<?php
//The function returns the no. of business days between two dates and it skeeps the holidays
function getWorkingDays($startDate,$endDate,$holidays){
   
//The total number of days between the two dates. We compute the no. of seconds and divide it to 60*60*24
    //We add one to inlude both dates in the interval.
   
$days = (strtotime($endDate) - strtotime($startDate)) / 86400 + 1;

   
$no_full_weeks = floor($days / 7);
   
$no_remaining_days = fmod($days, 7);

   
//It will return 1 if it's Monday,.. ,7 for Sunday
   
$the_first_day_of_week = date("N",strtotime($startDate));
   
$the_last_day_of_week = date("N",strtotime($endDate));

   
//---->The two can be equal in leap years when february has 29 days, the equal sign is added here
    //In the first case the whole interval is within a week, in the second case the interval falls in two weeks.
   
if ($the_first_day_of_week <= $the_last_day_of_week){
        if (
$the_first_day_of_week <= 6 && 6 <= $the_last_day_of_week) $no_remaining_days--;
        if (
$the_first_day_of_week <= 7 && 7 <= $the_last_day_of_week) $no_remaining_days--;
    }
    else{
        if (
$the_first_day_of_week <= 6) $no_remaining_days--;
       
//In the case when the interval falls in two weeks, there will be a Sunday for sure
       
$no_remaining_days--;
    }

   
//The no. of business days is: (number of weeks between the two dates) * (5 working days) + the remainder
//---->february in none leap years gave a remainder of 0 but still calculated weekends between first and last day, this is one way to fix it
  
$workingDays = $no_full_weeks * 5;
    if (
$no_remaining_days > 0 )
    {
     
$workingDays += $no_remaining_days;
    }

   
//We subtract the holidays
   
foreach($holidays as $holiday){
       
$time_stamp=strtotime($holiday);
       
//If the holiday doesn't fall in weekend
       
if (strtotime($startDate) <= $time_stamp && $time_stamp <= strtotime($endDate) && date("N",$time_stamp) != 6 && date("N",$time_stamp) != 7)
           
$workingDays--;
    }

    return
$workingDays;
}

//Example:

$holidays=array("2006-12-25","2006-12-26","2007-01-01");

echo
getWorkingDays("2006-12-22","2007-01-06",$holidays)
// => will return 8
?>

Otherwise, I found this very useful, thanks marius:)
Bill at wLathrop com
13-Dec-2007 04:56
For JasonLFunk

I did some testing on the occurrence for a given date within the month (i.e 1st Monday, 2nd Wednesday, 3rd Friday, etc.).

where $dDate is a getdate() array

intval(($dDate['mday']-1)/7)+1 

Returns an integer representing the week for a given date.  I tested on a complete calendar month and it seems to work well.

I then convert to a string and compare to a string list of values to see if it is in the list.  If it is - it qualifies.  So, my list of values might be '2,4' representing every 2nd and 4th occurrence.
bikinyboy at example dot com
11-Dec-2007 07:44
This function is like date, but it "speaks" Hungarian (or an other language)

<?php
/*
  these are the hungarian additional format characters
  ö: full textual representation of the day of the week
  Ö: full textual representation of the day of the week (first character is uppercase),
  ő: short textual representation of the day of the week,
  Ő: short textual representation of the day of the week (first character is uppercase),
  ü: full textual representation of a month
  Ü: full textual representation of a month (first character is uppercase),
  ű: short textual representation of a month
  Ű: short textual representation of a month (first character is uppercase),
*/
function date_hu($formatum, $timestamp=0) {
  if ((
$timestamp <= -1) || !is_numeric($timestamp)) return '';
 
$q['ö'] = array(-1 => 'w', 'vasárnap', 'hétfő', 'kedd', 'szerda', 'csütörtök', 'péntek', 'szombat');
 
$q['Ö'] = array(-1 => 'w', 'Vasárnap', 'Hétfő', 'Kedd', 'Szerda', 'Csütörtök', 'Péntek', 'Szombat');
 
$q['ő'] = array(-1 => 'w', 'va', 'hé', 'ke', 'sze', 'csü', 'pé', 'szo');
 
$q['Ő'] = array(-1 => 'w', 'Va', 'Hé', 'Ke', 'Sze', 'Csü', 'Pé', 'Szo');
 
$q['ü'] = array(-1 => 'n', '', 'január', 'február', 'március', 'április', 'május', 'június', 'július', 'augusztus', 'szeptember', 'október', 'november', 'december');
 
$q['Ü'] = array(-1 => 'n', '', 'Január', 'Február', 'Március', 'Április', 'Május', 'Június', 'Július', 'Augusztus', 'Szeptember', 'Október', 'November', 'December');
 
$q['ű'] = array(-1 => 'n', '', 'jan', 'febr', 'márc', 'ápr', 'máj', 'júni', 'júli', 'aug', 'szept', 'okt', 'nov', 'dec');
 
$q['Ű'] = array(-1 => 'n', '', 'Jan', 'Febr', 'Márc', 'Ápr', 'Máj', 'Júni', 'Júli', 'Aug', 'Szept', 'Okt', 'Nov', 'Dec');

  if (
$timestamp == 0)
   
$timestamp = time();
 
$temp = '';
 
$i = 0;
  while ( (
strpos($formatum, 'ö', $i) !== FALSE) || (strpos($formatum, 'Ö', $i) !== FALSE) ||
          (
strpos($formatum, 'ő', $i) !== FALSE) || (strpos($formatum, 'Ő', $i) !== FALSE) ||
          (
strpos($formatum, 'ü', $i) !== FALSE) || (strpos($formatum, 'Ü', $i) !== FALSE) ||
          (
strpos($formatum, 'ű', $i) !== FALSE) || (strpos($formatum, 'Ű', $i) !== FALSE)) {
   
$ch['ö']=strpos($formatum, 'ö', $i);
   
$ch['Ö']=strpos($formatum, 'Ö', $i);
   
$ch['ő']=strpos($formatum, 'ő', $i);
   
$ch['Ő']=strpos($formatum, 'Ő', $i);
   
$ch['ü']=strpos($formatum, 'ü', $i);
   
$ch['Ü']=strpos($formatum, 'Ü', $i);
   
$ch['ű']=strpos($formatum, 'ű', $i);
   
$ch['Ű']=strpos($formatum, 'Ű', $i);
    foreach (
$ch as $k=>$v)
      if (
$v === FALSE)
        unset(
$ch[$k]);
   
$a = min($ch);
   
$temp .= date(substr($formatum, $i, $a-$i), $timestamp) . $q[$formatum[$a]][date($q[$formatum[$a]][-1], $timestamp)];
   
$i = $a+1;
  }
 
$temp .= date(substr($formatum, $i), $timestamp);
  return
$temp;
}

echo
date_hu('Y. ü j. (ö) G:i');
?>
redcore at gmail dot com
19-Nov-2007 05:24
For those of us who don't have 5.x installed (that puts a colon in the time zone)...

<?php
$timezone
= date("O"); // get timezone
$timezone_end = substr($timezone, -2, 2); // get last two numbers
$timezone= substr($timezone, 0, -2); // get first half
echo $timezone = $timezone . ":" . $timezone_end; // add colon
?>
info at NOSPAM dot ogmatter dot com
29-Oct-2007 07:30
Hello, these notes have been very helpful and help me solve the following problem.

I have a db with scheduled items that contain a start date, a day to occur on and how many weeks from the next closest day to happen again.  I wrote the following script to do the following
1. Accept : starting date, the current date, the number of weeks between occurances and the day of the week it is to occur on.
2. Find the closest future day of the week argument from the start date.
3. Find out when the next time the item should happen via the weeks inbetween and the closest day of the week to the start date.

The result could be compared with your current date to trigger your periodical item or simply to find out when the next occurances will happen.

// $startDate:Date
// $todayDate:Date
// $weeks:Int - number of weeks in between
// $wantDay:String - full day of the week
function getWeekPeriodDate($startDate,$todayDate,$weeks,$wantDay){
  $startDate = date("Y-m-d", strtotime("next $wantDay" ,strtotime($startDate)));
  $dayDiff = round((strtotime($startDate)-strtotime($todayDate))/(24*60*60),0);
  $weekPeriodDiff = abs(round($dayDiff/7/$weeks)*$weeks);
  return date("Y-m-d",strtotime($startDate . " + " . $weekPeriodDiff . " weeks"));
}

Usage :getWeekPeriodDate("2006-July-1","2007-Nov-5",8,"Tuesday")
returns : 2007-11-20 (which is the next Tuesday based on 8 week periods since the next Tuesday closest to the start date)
snobord787 at msn dot com
29-Aug-2007 09:06
I modified (erenezgu at gmail.com)'s code so you don't have to redirect but is stored in cookies.

<?php
if(empty($_COOKIE['offset'])) {
   
// Javascript is our friend!
   
$header='
<script type="text/javascript">
document.cookie="offset=" + ( (new Date()).getTimezoneOffset()*60)*(-1)-'
.abs(date('Z')).';
</script>
'
;
}

// Example Usage
echo date('d/m/Y H:i:s', time()+$_COOKIE['offset'] );
?>
jasonlfunk (at) gmail dot com
10-Aug-2007 12:39
If there is an easier way to find the week of the month, let me know. Here is how I figured out how to do it;

date("W") - date("W",strtotime(date("F") . " 1st " . date("Y"))) + 1;
luis dot sv at gmail dot com
20-Jul-2007 11:00
In relation to soreenpk at yahoo dot com's message:

That code doesn't work for two dates with a difference larger than a year, for example:
$digest_date = "2006-04-14";
$date2="2007-04-15";
$date_diff = date("d",strtotime($date2)) - date("d",strtotime($digest_date));//$date_diff = 1
samuel at islabinaria dot com
15-Jul-2007 07:18
Here is a backward compatible version of dates_interconv
http://www.php.net/manual/en/function.date.php#71397
which also works with time (hours, minutes and seconds) and months in "M" format (three letters):

<?php
 
/**
   mod of
   http://www.php.net/manual/en/function.date.php#71397
   * Converts a date and time string from one format to another (e.g. d/m/Y => Y-m-d, d.m.Y => Y/d/m, ...)
   *
   * @param string $date_format1
   * @param string $date_format2
   * @param string $date_str
   * @return string
  */
 
function dates_interconv($date_format1, $date_format2, $date_str)
  {

     
$base_struc     = split('[:/.\ \-]', $date_format1);
     
$date_str_parts = split('[:/.\ \-]', $date_str );
    
     
// print_r( $base_struc ); echo "\n"; // for testing
      // print_r( $date_str_parts ); echo "\n"; // for testing
    
     
$date_elements = array();
    
     
$p_keys = array_keys( $base_struc );
      foreach (
$p_keys as $p_key )
      {
          if ( !empty(
$date_str_parts[$p_key] ))
          {
             
$date_elements[$base_struc[$p_key]] = $date_str_parts[$p_key];
          }
          else
              return
false;
      }
    
     
// print_r($date_elements); // for testing
     
     
if (array_key_exists('M', $date_elements)) {
       
$Mtom=array(
         
"Jan"=>"01",
         
"Feb"=>"02",
         
"Mar"=>"03",
         
"Apr"=>"04",
         
"May"=>"05",
         
"Jun"=>"06",
         
"Jul"=>"07",
         
"Aug"=>"08",
         
"Sep"=>"09",
         
"Oct"=>"10",
         
"Nov"=>"11",
         
"Dec"=>"12",
        );
       
$date_elements['m']=$Mtom[$date_elements['M']];
      }
     
     
// print_r($date_elements); // for testing
    
     
$dummy_ts = mktime(
       
$date_elements['H'],
       
$date_elements['i'],
       
$date_elements['s'],
       
$date_elements['m'],
       
$date_elements['d'],
       
$date_elements['Y']
      );
    
      return
date( $date_format2, $dummy_ts );
  }
?>

Usage:

<?php
  $df_src
= 'd/m/Y H:i:s';
 
$df_des = 'Y-m-d H:i:s';
 
  echo
dates_interconv( $df_src, $df_des, '25/12/2005 23:59:59');
?>

Output:

2005-12-25 23:59:59
pierrotevrard at gmail dot com
03-Jul-2007 04:11
For people who used "z" format...

The real range of "z" key format is 0 to 365 (instead of 366) and "z" represent the number of spent days in the year.
See this examples :

<?php
define
("\n" , NL );
print
'<pre>';

print
'"z" format interpretation:' . NL . NL;

print
'On 0 timestamp: "' . date( 'z : Y-m-d' , 0 ) . '"' . NL;
//show: On 0 timestamp: "0 : 1970-01-01"

print 'On second unix day: "' . date( 'z : Y-m-d' , 3600*24 ) . '"' . NL;
//show: On second unix day: "1 : 1970-01-02"

print 'On the last day of a leap year: "' . date( 'z : Y-m-d' , mktime( 23, 59, 59, 12, 31, 2000 ) ) . '"' . NL;
//show: On the last