i hate working with dates

This little snippet gets all the days in a month, and groups them by week.

<?php

    error_reporting(E_ALL);

    // Return an array of all the days in a month grouped by week number
    // (Sunday is considered to be the first day of the week)
    function weeksInMonth($month, $year)
    {
        $firstDay    = mktime(0, 0, 0, $month, 1, $year);
        $daysInMonth = date('t', $firstDay);
       
        $week        = 1;
        $breakdown   = array();
       
        for($i = 1; $i <= $daysInMonth; $i++)
        {
            $date = mktime(0, 0, 0, $month, $i, $year);
            $day  = date('l', $date);
           
            // Sunday triggers the start of a new week, except if it's
            // also the first day of the month.
            if(($day == 'Sunday') && ($i != 1))
            {
                $week++;
            }
           
            $breakdown[$week][] = $date;
        }
       
        return $breakdown;
    }
   
   
    $results = monthToWeek(6, 2008);
   
    printf("There are %d weeks in June 2008\n\n", count($results));
   
    foreach($results as $weekNumber => $days)
    {
        printf("Week %d\n", $weekNumber);
       
        foreach($days as $day)
        {
            printf("%10s  %s\n", date("l", $day), date("Y-m-d", $day));
        }
       
        printf("\n");
    }

/*
There are 5 weeks in June 2008

Week 1
    Sunday  2008-06-01
    Monday  2008-06-02
   Tuesday  2008-06-03
 Wednesday  2008-06-04
  Thursday  2008-06-05
    Friday  2008-06-06
  Saturday  2008-06-07

Week 2
    Sunday  2008-06-08
    Monday  2008-06-09
   Tuesday  2008-06-10
 Wednesday  2008-06-11
  Thursday  2008-06-12
    Friday  2008-06-13
  Saturday  2008-06-14

Week 3
    Sunday  2008-06-15
    Monday  2008-06-16
   Tuesday  2008-06-17
 Wednesday  2008-06-18
  Thursday  2008-06-19
    Friday  2008-06-20
  Saturday  2008-06-21

Week 4
    Sunday  2008-06-22
    Monday  2008-06-23
   Tuesday  2008-06-24
 Wednesday  2008-06-25
  Thursday  2008-06-26
    Friday  2008-06-27
  Saturday  2008-06-28

Week 5
    Sunday  2008-06-29
    Monday  2008-06-30
*/

?>

This entry was posted on Thursday, August 21st, 2008 at 11:45 am and is filed under php, programming. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply