Skip to content

Instantly share code, notes, and snippets.

@kadet1090
Created March 30, 2016 15:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kadet1090/cd0afbf0be9f6a69cd2d3d22d7079b71 to your computer and use it in GitHub Desktop.
Save kadet1090/cd0afbf0be9f6a69cd2d3d22d7079b71 to your computer and use it in GitHub Desktop.
Simple month padder for calendars etc.
<?php
use Carbon\Carbon;
use Carbon\CarbonInterval;
/**
* Pads given month to whole weeks.
*
* @param int $year Year
* @param int $month Month
* @param int|string $firstDay First day of week index (0 for sunday) or name.
*
* @return DatePeriod[]
*/
function paddedMonth($year, $month, $firstDay = 0) {
if(is_string($firstDay)) {
$firstDay = array_search($firstDay, ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']);
}
$current = Carbon::createFromDate($year, $month, 1);
$current->subDays($current->weekDay - $firstDay);
$weeks = [];
do {
$weeks[] = new DatePeriod(clone $current, CarbonInterval::day(), $current->addWeek());
} while($current->month == $month);
return $weeks;
}
<?php
/**
* Pads given month to whole weeks.
*
* @param int $year Year
* @param int $month Month
* @param int|string $firstDay First day of week index (0 for sunday) or name.
*
* @return DatePeriod[]
*/
function paddedMonth($year, $month, $firstDay = 0)
{
if (is_string($firstDay)) {
$firstDay = array_search(
$firstDay, ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
);
}
$current = DateTime::createFromFormat('d.m.Y', "1.$month.$year");
$current->modify('-' . ($current->format('w') - $firstDay) . ' day');
$weeks = [];
do {
$weeks[] = new DatePeriod(clone $current, new DateInterval('P1D'), $current->modify('+1 week'));
} while ($current->format('m') == $month);
return $weeks;
}
<?php
foreach (padMonth(2016, 3) as $week) {
foreach ($week as $day) {
echo $day->format('d') . "\t";
}
echo PHP_EOL;
}
# 29 01 02 03 04 05 06
# 07 08 09 10 11 12 13
# 14 15 16 17 18 19 20
# 21 22 23 24 25 26 27
# 28 29 30 31 01 02 03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment