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

search for in the

getdate> <date_timezone_set
Last updated: Fri, 14 Nov 2008

view this page in

date

(PHP 4, PHP 5)

dateFormata a data e a hora local

Descrição

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

Retorna uma string de acordo com a string format dada usando o inteiro timestamp dado ou a hora atual local se nenhum timestamp é dado. Em outras palavras, timestamp é opcional e o padrão para o valor de time().

Parâmetros

format

A string de formato da data a ser mostrada. Veja as opções de formatação abaixo.

Os seguintes caracteres são reconhecidos na string do parâmetro format
Caractere de format Descrição Exemplo de valores retornados
Day --- ---
d Dia do mês, 2 digitos com preenchimento de zero 01 até 31
D Uma representação textual de um dia, três letras Mon até Sun
j Dia do mês sem preenchimento de zero 1 até 31
l ('L' minúsculo) A representação textual completa do dia da semana Sunday até Saturday
N Representação numérica ISO-8601 do dia da semana (adicionado no PHP 5.1.0) 1 (para Segunda) até 7 (para Domingo)
S Sufixo ordinal inglês para o dia do mês, 2 caracteres st, nd, rd ou th. Funciona bem com j
w Representação numérica do dia da semana 0 (para domingo) até 6 (para sábado)
z O dia do ano (começando do 0) 0 through 365
Semana --- ---
W Número do ano da semana ISO-8601, semanas começam na Segunda (adicionado no PHP 4.1.0) Exemplo: 42 (the 42nd week in the year)
Mês --- ---
F Um representação completa de um mês, como January ou March January até December
m Representação numérica de um mês, com leading zeros 01 a 12
M Uma representação textual curta de um mês, três letras Jan a Dec
n Representação numérica de um mês, sem leading zeros 1 a 12
t Número de dias de um dado mês 28 through 31
Year --- ---
L Se está em um ano bissexto 1 se está em ano bissexto, 0 caso contrário.
o Número do ano ISO-8601. Este tem o mesmo valor como Y, exceto que se o número da semana ISO (W) pertence ao anterior ou próximo ano, o ano é usado ao invés. (adicionado no PHP 5.1.0) Exemplos: 1999 ou 2003
Y Uma representação de ano completa, 4 dígitos Exemplos: 1999 ou 2003
y Uma representação do ano com dois dígitos Exemplos: 99 ou 03
Tempo --- ---
a Antes/Depois de meio-dia em minúsculo am or pm
A Antes/Depois de meio-dia em maiúsculo AM or PM
B Swatch Internet time 000 até 999
g Formato 12-horas de uma hora sem preenchimento de zero 1 até 12
G Formato 24-horas de uma hora sem preenchimento de zero 0 até 23
h Formato 12-horas de uma hora com zero preenchendo à esquerda 01 até 12
H Formato 24-horas de uma hora com zero preenchendo à esquerda 00 até 23
i Minutos com zero preenchendo à esquerda 00 até 59
s Segundos, com zero preenchendo à esquerda 00 até 59
u Milisegundos (adicionado no PHP 5.2.2) Exemplo: 54321
Timezone --- ---
e Identificador de Timezone (adicionado no PHP 5.1.0) Exemplos: UTC, GMT, Atlantic/Azores
I (capital i) Se a data está ou não no horário de verão 1 se horário de verão, 0 caso contrário.
O Diferença para Greenwich time (GMT) em horas Exemplo: +0200
P Diferença para Greenwich time (GMT) com dois pontos entre horas e minutos (adicionado no PHP 5.1.3) Exemplo: +02:00
T Abreviação de Timezone Exemplos: EST, MDT ...
Z Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. -43200 até 50400
Full Date/Time --- ---
c ISO 8601 date (adicionado no PHP 5) 2004-02-12T15:19:21+00:00
r » RFC 2822 formatted date Exemplo: Thu, 21 Dec 2000 16:01:07 +0200
U Segundos desde a Época Unix (January 1 1970 00:00:00 GMT) Veja também time()

Caracteres não reconhecidos no formato de serão impressos como são. O formato Z será sempre retornado 0 quando usar gmdate().

Nota: Desde que esta função aceita somente integer timestamps o caractere de formato u é somente útil quando usando a função date_format() com um timestamp baseado pelo usuário criado com date_create().

timestamp

O parâmetro opcional timestamp é um integer Unix timestamp cujo padrão é a hora local se timestamp não for dado. Em outras palavras, o padrão é o valor de time().

Valor Retornado

Retorna um string da data formatada. Se um valor não-numérico é usado para timestamp , FALSE é retornado e um erro de nível E_WARNING é emitido.

Erros

Toda a chamada a uma função de data/hora irá gerar um se a zona da hora não for valida, e/ou uma mensagem E_STRICT se estiver usando a definição do sistema ou a variável de ambiente TZ. Veja também date_default_timezone_set()

Histórico

Versão Descrição
5.1.0 O intervalo válido de um timestamp é tipicamente de Sex, 13 Dez 1901 20:45:54 GMT to Ter, 19 Jan 2038 03:14:07 GMT. (Estas são as datas que correspondem ao valor mínimo e máximo para um inteiro com sinal de 32-bit). Contudo, antes do PHP 5.1.0 este intervalo foi limitado de 01-01-1970 para 19-01-2038 em alguns sistemas (e.g. Windows).
5.1.0

Agora emite E_STRICT e E_NOTICE em erros da zona de horário.

5.1.1 constantes útils do padrão de formato de data/hora que podem ser usados para especificar o parâmetro format .

Exemplos

Exemplo #1 Exemplos da date()

<?php
// Modifica a zona de tempo a ser utilizada. Disnovível desde o PHP 5.1
date_default_timezone_set('UTC');


// Exibe alguma coisa como: Monday
echo date("l");

// Exibe alguma coisa como: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');

// Exibe: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " date("l"mktime(000712000));

/* utiliza as constantes do parâmetro de formato */
// Exibe alguma coisa como: Mon, 15 Aug 2005 15:12:46 UTC
echo date(DATE_RFC822);

// Exibe alguma coisa como: 2000-07-01T00:00:00+00:00
echo date(DATE_ATOMmktime(000712000));
?>

Você pode prevenir um caracter conhecido no formato de string de um existente escapando-o com uma barra invertida antes dele. Se o caracter com a barra invertida já é uma sequência especial, você pode precisar também escapar a barra invertida.

Exemplo #2 Caracteres de escape em date()

<?php
// exibe algo como: Wednesday the 15th
echo date("l \\t\h\e jS");
?>

É possível utilizar date() e mktime() juntos para encontrar datas no futuro ou no passado.

Exemplo #3 Exemplo da date() e mktime()

<?php
$tomorrow  
mktime (000date("m")  , date("d")+1date("Y"));
$lastmonth mktime (000date("m")-1date("d"),  date("Y"));
$nextyear  mktime (000date("m"),  date("d"),  date("Y")+1);
?>

Nota: Esta pode ser mais confiável do que simplesmente adicionar ou subtrair o número de segundos em um dia ou mês para um timestamp devido ao horário de verão.

Alguns exemplos de formatação de date(). Note que você poderia escapar qualquer outro caracter, como algum que atualmente tenha um significado especial produzirá resultados indesejáveis, e outros caracteres poderiam assumir significados em futuras versões do PHP. Quando usar escape, certifique o uso de aspas simples para evitar caracteres como \n próprio para novas linhas.

Exemplo #4 Formatação de date()

<?php
// Assumindo que hoje é: March 10th, 2001, 5:16:18 pm

$today date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$today date("m.d.y");                         // 03.10.01
$today date("j, n, Y");                       // 10, 3, 2001
$today date("Ymd");                           // 20010310
$today date('h-i-s, j-m-y, it is w Day z ');  // 05-16-17, 10-03-01, 1631 1618 6 Fripm01
$today date('\i\t \i\s \t\h\e jS \d\a\y.');   // It is the 10th day.
$today date("D M j G:i:s T Y");               // Sat Mar 10 15:16:08 MST 2001
$today date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:17 m is month
$today date("H:i:s");                         // 17:16:17
?>

Para formatar datas em outras línguas, você usaria as funções setlocale() e strftime() ao invés de date().

Notas

Nota: Para gerar um timestamp de uma string da representação da data, você pode usar strtotime(). Adicionalmente, alguns banco de dados tem funções para converter os formatos de data para timestamps (como a função » UNIX_TIMESTAMP do MySQL).

Dica

Timestamp do início da requisição está disponível na $_SERVER['REQUEST_TIME'] desde o PHP 5.1.



getdate> <date_timezone_set
Last updated: Fri, 14 Nov 2008
 
add a note add a note User Contributed Notes
date
sourabhshankar AT gmail DOT com
14-Nov-2008 12:43
<?php
/*
Find out start and end date of current week.
I am assuming that week starts at sunday and ends at saturday.
so a typical week will look like this: sun,mon,tue,wed,thu,fri,sat
if you find any bug/error, please email me.
*/

//sunday = start of week
$sat = 6; //saturday = end of week
$current_day=date('w');
$days_remaining_until_sat = $sat - $current_day;

$ts_start = strtotime("-$current_day days");
$ts_end = strtotime("+$days_remaining_until_sat days");

echo
date('m-d-Y',$ts_start); //start date
echo '<br>';
echo
date('m-d-Y',$ts_end); //end date

/*
OUTPUT (m-d-y):
11-09-2008
11-15-2008
*/
?>
tchapin at gmail dot com
09-Nov-2008 10:26
<?php
   
// Function used to take two date strings, and returns an associative array
    // with different formats for the difference between the dates.
    // --------------------
    // Variables:
    // StartDateString (String - MM/DD/YYYY)
    // EndDateString (String - MM/DD/YYYY)
    // --------------------
    // Example: $DateDiffAry = GetDateDifference('01/09/2008', '02/11/2009');
    // print_r($DateDiffAry);
    // --------------------
    // Returns Something Like:
    /*   
    Array
    (
        [YearsSince] => 1.0931506849315
        [MonthsSince] => 13.117808219178
        [DaysSince] => 399
        [HoursSince] => 9576
        [MinutesSince] => 574560
        [SecondsSince] => 34473600
        [NiceString] => 1 year, 1 month, and 2 days
        [NiceString2] => Years: 1, Months: 1, Days: 2
    )
    */

   
function GetDateDifference($StartDateString=NULL, $EndDateString=NULL) {
       
$ReturnArray = array();
       
       
$SDSplit = explode('/',$StartDateString);
       
$StartDate = mktime(0,0,0,$SDSplit[0],$SDSplit[1],$SDSplit[2]);
       
       
$EDSplit = explode('/',$EndDateString);
       
$EndDate = mktime(0,0,0,$EDSplit[0],$EDSplit[1],$EDSplit[2]);
       
       
$DateDifference = $EndDate-$StartDate;
       
       
$ReturnArray['YearsSince'] = $DateDifference/60/60/24/365;
       
$ReturnArray['MonthsSince'] = $DateDifference/60/60/24/365*12;
       
$ReturnArray['DaysSince'] = $DateDifference/60/60/24;
       
$ReturnArray['HoursSince'] = $DateDifference/60/60;
       
$ReturnArray['MinutesSince'] = $DateDifference/60;
       
$ReturnArray['SecondsSince'] = $DateDifference;

       
$y1 = date("Y", $StartDate);
       
$m1 = date("m", $StartDate);
       
$d1 = date("d", $StartDate);
       
$y2 = date("Y", $EndDate);
       
$m2 = date("m", $EndDate);
       
$d2 = date("d", $EndDate);
       
       
$diff = '';
       
$diff2 = '';
        if ((
$EndDate - $StartDate)<=0) {
           
// Start date is before or equal to end date!
           
$diff = "0 days";
           
$diff2 = "Days: 0";
        } else {

           
$y = $y2 - $y1;
           
$m = $m2 - $m1;
           
$d = $d2 - $d1;
           
$daysInMonth = date("t",$StartDate);
            if (
$d<0) {$m--;$d=$daysInMonth+$d;}
            if (
$m<0) {$y--;$m=12+$m;}
           
$daysInMonth = date("t",$m2);
           
           
// Nicestring ("1 year, 1 month, and 5 days")
           
if ($y>0) $diff .= $y==1 ? "1 year" : "$y years";
            if (
$y>0 && $m>0) $diff .= ", ";
            if (
$m>0) $diff .= $m==1? "1 month" : "$m months";
            if ((
$m>0||$y>0) && $d>0) $diff .= ", and ";
            if (
$d>0) $diff .= $d==1 ? "1 day" : "$d days";
           
           
// Nicestring 2 ("Years: 1, Months: 1, Days: 1")
           
if ($y>0) $diff2 .= $y==1 ? "Years: 1" : "Years: $y";
            if (
$y>0 && $m>0) $diff2 .= ", ";
            if (
$m>0) $diff2 .= $m==1? "Months: 1" : "Months: $m";
            if ((
$m>0||$y>0) && $d>0) $diff2 .= ", ";
            if (
$d>0) $diff2 .= $d==1 ? "Days: 1" : "Days: $d";
           
        }
       
$ReturnArray['NiceString'] = $diff;
       
$ReturnArray['NiceString2'] = $diff2;
        return
$ReturnArray;
    }
   
   
// Example:
   
$DateDiffAry = GetDateDifference('01/09/2008', '02/11/2009');
   
print_r($DateDiffAry);
   
?>
Grapsus
02-Nov-2008 03:38
Here's a small function which returns TRUE if European Summer Time is used (now or at a given date) :

<?php
if(!function_exists('estdst'))
{
  function
estdst($ts=false)
  {
   
$ts = $ts?$ts:time();
   
$year = gmdate('Y', $ts);
   
$end = gmmktime(1, 0, 0, 3, 31 - ((5 * $year) / 4 + 4)%7, $year);
   
$start = gmmktime(1, 0, 0, 10, 31 - ((5 * $year) / 4 + 1)%7, $year);
    return
$ts < $end || $ts > $start;
  }
}
?>

Calculation formula taken from here : http://en.wikipedia.org/wiki/European_Summer_Time
robertk113 at comcast dot net
31-Oct-2008 01:46
I need to display graphic-A during hours 1-9 and graphic-B during hours 10-24. Anybody know of a simple way to do this? Better yet, if we can select times based upon the day of the week, it would be even better!

I tried searching, but didn't inf anything resembling this. The coding will be added to a product description in osCommerce, which accepts html coding easily but other scripting types may or may not work. I want an OPEN graphic to display during normal business hours, and CLOSED when outside these hours.

Thanks in advance!
kyle renfrow
22-Oct-2008 06:41
i figured i would post this, it's only useful for systems dealing with UTC and EST, but could easily be modified to support multiple timezones. this function will tell you whether it's daylight saving time for the eastern timezone using UTC localtime:

<?php
//checks whether DST in EST using UTC
//can pass $time in unix timestamp, otherwise uses time()
function est_isdst($time=NULL){
  if(!
$time) { $now = time(); }else { $now = $time; }
  if (
      
$now > strtotime(date('Y-m-d 6:59:59', strtotime('next Sunday', strtotime(date('Y', $now).'-3-7')))) &&
      
$now < strtotime(date('Y-m-d 6:00', strtotime('first Sunday', strtotime(date('Y', $now).'-11-0'))))
     ) { return
true; }else { return false; }
}
?>

USAGE:
<?php
if(est_isdst()) { echo 'Its DST in EST Timezone!'; }
?>
adityabhai [at] gmail [dot] com
07-Oct-2008 02:56
Aditya Bhatt (adityabhai [at] gmail [dot] com):

I have one date, and i want the next day of that date:

<?php

echo date("D F d Y",strtotime("+1 days")); // Same applies for months e.g. "+1 months"

?>

I have one date, and i want the previous day of that date:

<?php

echo date("D F d Y",strtotime("-1 days")); // Same applies for months e.g. "-1 months"

?>
Kenneth Kin Lum
02-Oct-2008 03:52
date(DATE_RFC822) and date(DATE_RFC2822) both work.  note that RFC 822 is obsoleted by RFC 2822.  The main difference is the year being 08 in RFC 822 and is 2008 in RFC 2822.

To use date(DATE_RFC2822), a short form is date('r').
nick at nick-web dot co dot uk
25-Sep-2008 08:48
RE: wulf dot kaiser at mpimf-heidelberg dot mpg dot de code to work out fridays in a month. I noticed one small error. It looks like the
<?php
if ($givenMonth != '12') {

   
$nextGivenMonth = "1";
   
$nextGivenYear = $givenYear + 1;}
?>
block was setting every month to 1 because it was not equal to 12. I changed that to <?php if ($givenMonth == '12') { ?>and now all is fine!

Now - to refine it so that it only shows Fridays on the 5th or after, until the 4th of the next month.. Damm UK tax stuff!

=)
N
Anonymous
24-Sep-2008 04:35
MySQL 5 will accept ISO_8601 encoded time, so it is acceptable to use date(ISO_8601)
Anonymous
12-Sep-2008 06:01
Correct format for a MySQL DATETIME column is
<?php $mysqltime = date ("Y-m-d H:i:s", $phptime); ?>
Cortexd
27-Aug-2008 11:47
a date function supporting the milliseconds format character

<?php
function udate($format, $utimestamp = null)
{
    if (
is_null($utimestamp))
       
$utimestamp = microtime(true);

   
$timestamp = floor($utimestamp);
   
$milliseconds = round(($utimestamp - $timestamp) * 1000000);

    return
date(preg_replace('`(?<!\\\\)u`', $milliseconds, $format), $timestamp);
}

echo
udate('H:i:s.u'); // 19:40:56.78128
echo udate('H:i:s.u', 654532123.04546); // 16:28:43.45460
?>
pdubbb1 at gmail dot com
26-Aug-2008 05:32
here is the simpliest way to get the start and end date of the week;

<?php
$sdate
=date('c',strtotime(date('Y')."W".date('W')."0"));

$edate=date('c',strtotime(date('Y')."W".date('W')."7"));
?>

the format is for the string in strtotime is;
 
     2008W200

this stands for year - 2008, constant never changes - W, week number of the year - 20, day of the week - 0 for sunday, 1 for monday, etc....

so 2008W200 stands for the sunday of the 20th week of 2008. 

This will only work in php 5 or better
abazaba.ru
14-Aug-2008 03:53
All novices must be very carefull when working with timestamps as second values.
From first glance it looks like date("Y-m-d H:i:s",TIMESTAMP) will return correct date, based on "how much seconds gone from 1970".
But here is the feature, it'll be corrected time, according to LOCAL timezone.

So if you take a 25200 as timestamp (10 hours),
then on one server you'll get
1970-01-01 08:00:00
and on other server you'll get
1970-01-01 09:00:00
and so on.
Though you could expect 1970-01-01 10:00:00 in all cases, because if 25200 seconds gone from 1970-01-01 00:00:00 it obviously have to be 1970-01-01 10:00:00

I spend today 3 hours to correct scripts which were created with such error by previous programmer, so please, guys, don't make me work like this and remember about conversation to LOCAL time.
phprocks at aol dot com
06-Aug-2008 11:25
Try this for finding the difference in days between 2 dates/datetimes... take note though, date_parse requires PHP version 5.1.3 or higher.

<?php
/**
 * Finds the difference in days between two calendar dates.
 *
 * @param Date $startDate
 * @param Date $endDate
 * @return Int
 */
function dateDiff($startDate, $endDate)
{
   
// Parse dates for conversion
   
$startArry = date_parse($startDate);
   
$endArry = date_parse($endDate);

   
// Convert dates to Julian Days
   
$start_date = gregoriantojd($startArry["month"], $startArry["day"], $startArry["year"]);
   
$end_date = gregoriantojd($endArry["month"], $endArry["day"], $endArry["year"]);

   
// Return difference
   
return round(($end_date - $start_date), 0);
}
?>
JonathanCross.com
25-Jul-2008 01:22
<?php
// A demonstration of the new DateTime class for those
// trying to use dates before 1970 or after 2038.
?>
<h2>PHP 2038 date bug demo (php version <?php echo phpversion(); ?>)</h1>
<div style='float:left;margin-right:3em;'>
<h3>OLD Buggy date()</h3>
<?php
  $format
='F j, Y';
  for (
$i = 1900; $i < 2050; $i++) {
   
$datep = "$i-01-01";
   
?>
    Trying: <?php echo $datep; ?> = <?php echo date($format, strtotime($datep)); ?><br>
    <?
  }
?></div>
<div style='float:left;'>
  <h3>NEW DateTime Class (v 5.2+)</h3><?php
 
for ( $i = 1900; $i < 2050; $i++) {
   
$datep = "$i-01-01";
   
$date = new DateTime($datep);
   
?>
    Trying: <?php echo $datep; ?> = <?php echo $date->format($format); ?><br>
    <?
  }
?></div>
Rob A.
10-Jul-2008 09:38
Quick function for returning the names of the next 7 days of the week starting with today.

Returns an array that can be formatted to your liking.

<?php
/**
* Returns array of next 7 days starting with today
*
*/

function next_7_days() {
       
// create array of day names. You can change these to whatever you want
   
$days = array(
                           
'Monday',
                           
'Tuesday',
                           
'Wednesday',
                           
'Thursday',
                           
'Friday',
                           
'Saturday',
                           
'Sunday');
   
$today = date('N');
    for (
$i=1;$i<$today;$i++) {

               
// take the first element off the array
       
$shift = array_shift($days);

               
// ... and add it to the end of the array
       
array_push($days,$shift);
    }
       
// returns the sorted array
   
return $days;
}
?>

It basically takes an array starting with Monday and shifts each day to the end of the array until the first element in the array is today.
con_tobe at yahoo dot com
09-Jul-2008 08:46
Doing $w-- for months ending on Sat won't hurt (i.e. if you're counting weeks as is the case below), but halocastle's code is perfectly fine as is and quite fast.  He/she uses $w as a key for the $weeks array.  "Halo" does this BEFORE $w++, so $w-- is superfluous as the loop has already ended.  For May, 2008, I get 5 weeks as expected...

Array
(
    [1] => Array
        (
            [4] => 1
            [5] => 2
            [6] => 3
        )

    [2] => Array
        (
            [0] => 4
            [1] => 5

------------OMITTED-----------------

            [4] => 22
            [5] => 23
            [6] => 24
        )

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

)

I guess the one pit-fall of the code is if you overlap months, say the following year, then $m-- makes perfect since...I think (haven't gotten that far...yet).

I modified "Halo's" code to include months, too (this is from a snippet that produces a three month calendar, hence the outer $months loop, omitted here).

<?php
$m
= date('m');
$Y = date('Y');

// for() {months loop omitted
$var_date = mktime(0, 0, 0, $m, 1, $Y);
$month_name = date('F', $var_date);
$months[$month_name]['DAYS'] = date('t', $var_date);
$months[$month_name]['FIRST_DAY'] = date('w', $var_date);
//}
foreach($months as $month => $key) {
 
$weeks = array();
  for(
$i = 1, $j = $key['FIRST_DAY'], $w = 1;$i <= $key['DAYS'];$i++) {
   
$weeks[$w][$j] = $i;
   
$j++;
    if(
$j == 7) {
     
$j = 0;
     
$w++;
    }
  }
 
$months[$month]['WEEKS'] = $weeks;
}
?>

Enjoy!
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).

<?php
$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:

<?php
$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.

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

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

<?php
// 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
<?php
/**
     * 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