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, 10 Oct 2008

view this page in

date

(PHP 4, PHP 5)

dateFormat a local time/date

Description

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

Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time().

Parameters

format

The format of the outputted date string. See the formatting options below.

The following characters are recognized in the format parameter string
format character Description Example returned values
Day --- ---
d Day of the month, 2 digits with leading zeros 01 to 31
D A textual representation of a day, three letters Mon through Sun
j Day of the month without leading zeros 1 to 31
l (lowercase 'L') A full textual representation of the day of the week Sunday through Saturday
N ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0) 1 (for Monday) through 7 (for Sunday)
S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
w Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday)
z The day of the year (starting from 0) 0 through 365
Week --- ---
W ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0) Example: 42 (the 42nd week in the year)
Month --- ---
F A full textual representation of a month, such as January or March January through December
m Numeric representation of a month, with leading zeros 01 through 12
M A short textual representation of a month, three letters Jan through Dec
n Numeric representation of a month, without leading zeros 1 through 12
t Number of days in the given month 28 through 31
Year --- ---
L Whether it's a leap year 1 if it is a leap year, 0 otherwise.
o ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0) Examples: 1999 or 2003
Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
y A two digit representation of a year Examples: 99 or 03
Time --- ---
a Lowercase Ante meridiem and Post meridiem am or pm
A Uppercase Ante meridiem and Post meridiem AM or PM
B Swatch Internet time 000 through 999
g 12-hour format of an hour without leading zeros 1 through 12
G 24-hour format of an hour without leading zeros 0 through 23
h 12-hour format of an hour with leading zeros 01 through 12
H 24-hour format of an hour with leading zeros 00 through 23
i Minutes with leading zeros 00 to 59
s Seconds, with leading zeros 00 through 59
u Microseconds (added in PHP 5.2.2) Example: 54321
Timezone --- ---
e Timezone identifier (added in PHP 5.1.0) Examples: UTC, GMT, Atlantic/Azores
I (capital i) Whether or not the date is in daylight saving time 1 if Daylight Saving Time, 0 otherwise.
O Difference to Greenwich time (GMT) in hours Example: +0200
P Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3) Example: +02:00
T Timezone abbreviation Examples: 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 through 50400
Full Date/Time --- ---
c ISO 8601 date (added in PHP 5) 2004-02-12T15:19:21+00:00
r » RFC 2822 formatted date Example: Thu, 21 Dec 2000 16:01:07 +0200
U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) See also time()

Unrecognized characters in the format string will be printed as-is. The Z format will always return 0 when using gmdate().

Note: Since this function only accepts integer timestamps the u format character is only useful when using the date_format() function with user based timestamps created with date_create().

timestamp

The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().

Return Values

Returns a formatted date string. If a non-numeric value is used for timestamp , FALSE is returned and an E_WARNING level error is emitted.

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

ChangeLog

Version Description
5.1.0 The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer). However, before PHP 5.1.0 this range was limited from 01-01-1970 to 19-01-2038 on some systems (e.g. Windows).
5.1.0

Now issues the E_STRICT and E_NOTICE time zone errors.

5.1.1 There are useful constants of standard date/time formats that can be used to specify the format parameter.

Examples

Example #1 date() examples

<?php
// set the default timezone to use. Available since PHP 5.1
date_default_timezone_set('UTC');


// Prints something like: Monday
echo date("l");

// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');

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

/* use the constants in the format parameter */
// prints something like: Mon, 15 Aug 2005 15:12:46 UTC
echo date(DATE_RFC822);

// prints something like: 2000-07-01T00:00:00+00:00
echo date(DATE_ATOMmktime(000712000));
?>

You can prevent a recognized character in the format string from being expanded by escaping it with a preceding backslash. If the character with a backslash is already a special sequence, you may need to also escape the backslash.

Example #2 Escaping characters in date()

<?php
// prints something like: Wednesday the 15th
echo date("l \\t\h\e jS");
?>

It is possible to use date() and mktime() together to find dates in the future or the past.

Example #3 date() and mktime() example

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

Note: This can be more reliable than simply adding or subtracting the number of seconds in a day or month to a timestamp because of daylight saving time.

Some examples of date() formatting. Note that you should escape any other characters, as any which currently have a special meaning will produce undesirable results, and other characters may be assigned meaning in future PHP versions. When escaping, be sure to use single quotes to prevent characters like \n from becoming newlines.

Example #4 date() Formatting

<?php
// Assuming today is: 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
?>

To format dates in other languages, you should use the setlocale() and strftime() functions instead of date().

Notes

Note: To generate a timestamp from a string representation of the date, you may be able to use strtotime(). Additionally, some databases have functions to convert their date formats into timestamps (such as MySQL's » UNIX_TIMESTAMP function).

Tip

Timestamp of the start of the request is available in $_SERVER['REQUEST_TIME'] since PHP 5.1.



getdate> <date_timezone_set
Last updated: Fri, 10 Oct 2008
 
add a note add a note User Contributed Notes
date
adityabhai [at] gmail [dot] com
07-Oct-2008 10: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"

?>
adityabhai [at] gmail [dot] com
07-Oct-2008 10:52
Aditya Bhatt (adityabhai [at] gmail [dot] com):

I have the current date & time, with me or any other date for which i want to check the month.
I want to display the next month using date function, it can be very helpful and a simple way to do this:

<?php
echo date('F j, Y, g:i a');

echo
'<br />';

echo
date('F j, Y, g:i a', strtotime('+1 month')); // Here you can change '+1 month' to n number of months you required in some of your calculation.

?>
Kenneth Kin Lum
02-Oct-2008 11: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').
cservant at videotron dot ca
26-Sep-2008 04:14
This is a code to convert RSS pubDate to a timestamp.
A timestamp is an INT which is faster and easier to sort than VARCHAR.

<?php
function pubDate_to_timestamp($time){
  
//Thu, 21 Aug 2008 01:14:36 PDT
   //=> date("D, j M Y H:i:s T");

  
$time = explode(' ', $time);
  
$chrono = explode(':', $time[4]);

  
$month = array('Jan' => 1, 'Feb' => 2, 'Mar' => 3, 'Apr' => 4, 'May' => 5,
                 
'Jun' => 6, 'Jul' => 7, 'Aug' => 8, 'Sep' => 9, 'Oct' => 10,
                 
'Nov' => 11, 'Dec' => 12);

  
$mktime = mktime($chrono[0], $chrono[1], $chrono[2], $month[$time[2]], $time[1], $time[3], $time[5]);

   return
$mktime;
}
?>
nick at nick-web dot co dot uk
25-Sep-2008 04: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
Landito
25-Sep-2008 12:44
Changing the Timezones.
Europe/Germany to USA/East and change it back
I needed the actual time of NY. ;)

<?PHP
putenv
("TZ=EST5EDT");
$date = date("Ymd-H:i:s");
putenv("TZ=MEZ-1MESZ");
?>
Anonymous
25-Sep-2008 12:35
MySQL 5 will accept ISO_8601 encoded time, so it is acceptable to use date(ISO_8601)
dave dot artur at gmail dot com
24-Sep-2008 04:28
I see a lot of solutions to date math / difference / subtraction issues, here's something I found works and is much simpler than some of the other things here. Apparently converting date values to a string allows you to apply arithmatic to them.

------------------------------

<?php
// Load the length of a song in seconds
$songLength = $emerge->getSongValue($sID, "songLength");

// Find when 1 frame started playing the song and convert that value to a string
// This works when pulling a datetime value from SQL
$songStart = (string)($emerge->getListItem("eID", $eID, "startTime"));
$songStart = (string)strtotime($songStart);
// The above is slightly roundabout, but seems to be the trick to getting PHP to stop treating variables like date values and doing weird math.

// Find when the current frame was loaded.
// This works when just using PHP date/time values
$loadTime = (string)date("U");

// Calculate the difference in seconds and convert to a value for a refresh entry.
$timeDiff = $loadTime - $songStart;
$length = (($songLength - $timeDiff) * 1000);
?>
jonathancnewcomb at msn dot com
20-Sep-2008 09:11
The following is a function that will convert Unix Epoch to date format string.

<?PHP
// Function by Jonathan C Newcomb

function unix_to_date($date_format, $unix_epoch){

// Get current server GMT

$gmt = date('P');

$gmt_split = explode(':', $gmt);

$gmt_offset = $gmt_split[0];

$ret = date($date_format, mktime(0 + ($gmt_offset),0, $unix_epoch, 1, 1, 1970));

return
$ret;
}
?>
domi at lab-9 dot com
16-Sep-2008 08:14
<?php
#
# retrieve total count of weeks in a year
#
# param: (int) $year the year in which you wanna get the week count; if not int (for example from date('Y') it is automatically casted
#
# --- NOTE:
# seen a lot of stuff around but nothing as fast;
# mktime() is a very performant operation and the loop
# is executed max 13 times
#
#
# see: http://www.php.net/mktime
# see: http://www.php.net/intval
#
function total_weeks($year) {
    if(!
is_int($year)) $year = intval($year);
   
$i=31;
    while(
date('w', mktime(23,59,59,12,$i,$year)) != 0) $i--;
    return
date('W', mktime(23,59,59,12,$i,$year));
}
?>
Anonymous
12-Sep-2008 02:01
Correct format for a MySQL DATETIME column is
<?php $mysqltime = date ("Y-m-d H:i:s", $phptime); ?>
Cortexd
27-Aug-2008 07: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 01: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
rowe_a at glan-hafren dot ac dot uk
22-Aug-2008 10:16
simple code to get the date of the monday and sunday of the current week.

inspired by: wulf dot kaiser at mpimf-heidelberg dot mpg dot de

<?
$day
= date('d');
$wkday = date('l');
$month = date('m');
$year = date('Y');

switch(
$wkday) {
   
    case
'Monday': $numDaysToSun = 6; $numDaysToMon = 0; break;
    case
'Tuesday': $numDaysToSun = 5; $numDaysToMon = 1; break;
    case
'Wednesday': $numDaysToSun = 4; $numDaysToMon = 2; break;
    case
'Thursday': $numDaysToSun = 3; $numDaysToMon = 3; break;
    case
'Friday': $numDaysToSun = 2; $numDaysToMon = 4; break;
    case
'Saturday': $numDaysToSun = 1; $numDaysToMon = 5; break;
    case
'Sunday': $numDaysToSun = 0; $numDaysToMon = 6; break;   
}

echo
$wkday;
echo
" - ";
echo
$day;
echo
" - ";
echo
$month;
echo
" - ";
echo
$year;
echo
" - ";
echo
$numDaysToSun;
echo
" - ";
echo
$numDaysToMon;
echo
" - ";
echo
$monday = date('d-m-Y', mktime('0','0','0', $month, $day-$numDaysToMon, $year));
echo
" - ";
echo
$sunday = date('d-m-Y', mktime('0','0','0', $month, $day+$numDaysToSun, $year));
?>

headings:
Day(string) - day - month - year - days to sun - days from mon - monday date - sunday date
output:
Friday - 22 - 08 - 2008 - 2 - 4 - 18-08-2008 - 24-08-2008
abazaba.ru
14-Aug-2008 11: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 07: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);
}
?>
laszlo72 at gmail dot com
28-Jul-2008 11:16
if you want to get the number of month
between two dates
you can use this function:

<?php
/*

$start = "YYYYMM" ;
$stop = "YYYYMM" ;

*/

function getNumMonth($start,$stop) {

       
$aSta = substr($start,0,4) ;
       
$aSto = substr($stop,0,4) ;
       
       
$mSta = substr($start,4,2) ;
       
$mSto = substr($stop,4,2) ;
       
        if(
$aSta == $aSto) {             
            return
$mSto-$mSta+1 ;
        } else {
            if((
$aSto-$aSta) == 1) {    
                return
12-$mSta+$mSto+1 ;
            } else {                    
                return (
12-$mSta+$mSto+1)+($aSto-$aSta-1)*12;
            }   
        }
}
?>
JonathanCross.com
25-Jul-2008 09: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 <?= phpversion() ?>)</h1>
<div style='float:left;margin-right:3em;'>
<h3>OLD Buggy date()</h3>
<?
  $format
='F j, Y';
  for (
$i = 1900; $i < 2050; $i++) {
   
$datep = "$i-01-01";
   
?>
    Trying: <?=$datep?> = <?=date($format, strtotime($datep))?><br>
    <?
 
}
?></div>
<div style='float:left;'>
  <h3>NEW DateTime Class (v 5.2+)</h3><?
 
for ( $i = 1900; $i < 2050; $i++) {
   
$datep = "$i-01-01";
   
$date = new DateTime($datep);
   
?>
    Trying: <?=$datep?> = <?=$date->format($format)?><br>
    <?
 
}
?></div>
gertrude dot mendoza at gmail dot com
18-Jul-2008 08:41
<?php
/*
@params $firstdate, $lastdate
@return array() of array(monday,sunday)
@description returns all the mondays and sundays of the given date range
*/
function get_week_intervals($fdate,$ldate)
{
    list(
$year,$month,$day) = explode('-',$fdate);
   
$daynum = date('w',
                  
mktime(date('H'),
                         
date('i'),
                         
date('s'),
                         
$month,
                         
$day,
                         
$year)
                  );
   
$daynum = $daynum==0? 7 : $daynum;
   
$week=array();
   
//get the dayname of the first day
    //if month = current month get the current date as the last day
   
if($month==date('m'))
    {
       
$lastday = date('d');
    }
    else
    {
       
$lastday = date('t', strtotime($fdate));
    }
    if((
date('l',strtotime($fdate))) == 'Sunday')
    {
       
$monday = $fdate;
       
$sunday = $fdate;
    }
    else
    {
       
$monday = $fdate;
       
$sunday = date('Y-m-d',(mktime(date('H'),
                      
date('i'),date('s'),$month,
                      
$day,$year))-($daynum-7)*86400);

    }
   
$week[] = array('monday'=>$monday,'sunday'=>$sunday);

   
$day = date('d',strtotime($sunday." +1 day"));

    while(
$sunday < $ldate)
    {
       
$monday = date('Y-m-d',strtotime($sunday." +1 day"));

        list(
$year,$month,$day) = explode('-',$monday);
       
$daynum = date('w',
                     
mktime(date('H'),
                            
date('i'),
                            
date('s'),
                            
$month,
                            
$day,
                            
$year)
                       );
       
$daynum = $daynum==0? 7 : $daynum;

       
$sunday = date('Y-m-d',(mktime(date('H'),date('i'),
                      
date('s'),$month,$day,$year))-($daynum-7)*86400);
        if(
$sunday > $ldate)
        {
           
$sunday = $ldate;
        }

       
$week[] = array('monday'=>$monday,'sunday'=>$sunday);
    }

    return
$week;
}
?>
Anonymous
17-Jul-2008 05:30
to get the date of the monday from a week these function is useful:

<?php
/* Get First Calendar Week of Year x*/
 
function firstkw($jahr)
    {
      
$erster = mktime(0,0,0,1,1,$jahr);
      
$wtag = date('w',$erster);
    if (
$wtag <= 4) {
          
/**
            * Donnerstag oder kleiner: auf den Montag zurückrechnen.
            */
          
$montag = mktime(0,0,0,1,1-($wtag-1),$jahr);
       } else {
          
/**
            * auf den Montag nach vorne rechnen.
            */                                                                        
          
$montag = mktime(0,0,0,1,1+(7-$wtag+1),$jahr);
       }
       return
$montag;
    }

/*GET timestamp of monday of month x*/
   
function mondaykw($kwtime)
    {
          
$firstmonday =$this->firstkw(date("Y", $kwtime));
          
$mon_monat = date('m',$firstmonday);
          
$mon_jahr = date('Y',$firstmonday);
          
$mon_tage = date('d',$firstmonday);
          
$tage = (date("W", $kwtime)-1)*7;
          
$mondaykw = mktime(0,0,0,$mon_monat,$mon_tage+$tage,$mon_jahr);
           return
$mondaykw;
    }

echo
mondaykw(time()); //1215986400
?>
fgabrieli at gmail dot com
14-Jul-2008 08:56
here is a function to split a number of seconds in hours, minutes and seconds

<?php

   
function split_seconds($seconds)
    {
       
// get the minutes

       
$minutes = floor($seconds / 60) ;

       
$seconds_left = $seconds % 60 ;

       
// get the hours

       
$hours = floor($minutes / 60) ;

       
$minutes_left = $minutes % 60 ;

       
// (test) show the result 

       
echo "$hours hours $minutes_left minutes and $seconds_left seconds" ;
    }

   
split_seconds(68648) ;

?>
   

best regards
fernando gabrieli
shem_lexluger at yahoo.com
14-Jul-2008 01:43
Assuming a week starts on Monday. To calculate the week number of the current date starting from a specified date, use this function:

<?php
function weekcounter($start_date)
{
  
$start_date = strtotime($start_date);
  
$today = strtotime(date('d-m-Y'));

  
$week = 1;
   while(
$start_date < $today) {
   
$start_date = strtotime('next Monday', $start_date);
   
$week++;
   }

   return
$week;
}

// Example:
//now = 14-07-2008
echo weekcounter('01-07-2008'); //prints 3
echo weekcounter('01-06-2008'); //prints 8 instead of 7; because 1st jun is a Sunday so it is week 1 and 2nd june is week 2. Feel free to tweak.
?>
Rob A.
10-Jul-2008 05: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
10-Jul-2008 04: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
03-Jul-2008 03: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
01-Jul-2008 05: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