Skip to content

Instantly share code, notes, and snippets.

@tamboer
Last active December 14, 2015 21:39
Show Gist options
  • Save tamboer/5153141 to your computer and use it in GitHub Desktop.
Save tamboer/5153141 to your computer and use it in GitHub Desktop.
PHP - Common Date and Time functions
<?php
class Common_Datetime {
static public function months() {
$month_name_arr = array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
$month_name_arr = array("january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december");
return $month_name_arr;
}
/**
* return week start and end dates
*
* Please note that the first Monday of the year is not not necessarily the same thing as the Monday of ISO week 1.
* Week 1 is deemed to be the week that holds the first Thurday of a year.
* So, for example week 1 of 2013 will begin on 31/12/2013.
* en.wikipedia.org/wiki/ISO_week_date#First_week
* @param type $year
* @return array
*/
static public function week_starting_dates($year) {
$firstDayOfYear = mktime(0, 0, 0, 1, 1, $year);
$thursday = strtotime('thursday', $firstDayOfYear);
while (date('Y', $thursday) == $year) {
$monday = strtotime('previous monday', $thursday);
$sunday = strtotime('next sunday', $monday);
$week_starting_dates_arr[] = array(
'start'=> date('d/m',$monday),
'end' => date('d/m',$sunday));
//increment
$thursday = strtotime('+1 week',$thursday);
}
//Zend_Debug::dump($week_starting_dates_arr);exit;
return $week_starting_dates_arr;
}
static function weeknumber($date){
$ts = strtotime($date);
$weeknumber = (int)date('W', $ts);
return $weeknumber;
}
public function dateRange($first, $last, $step = '+1 day', $format = 'Y-m-d' ) {
$dates = array();
$current = strtotime($first);
$last = strtotime($last);
while( $current <= $last ) {
$dates[] = date($format, $current);
$current = strtotime($step, $current);
}
return $dates;
}
static function week_range($date) {
$ts = strtotime($date);
$wd = date('w', $ts);
if ($wd == 1) {
$start = strtotime('today', $ts);
} else {
$start = strtotime('last monday', $ts);
}
$week_start_end = array(
date('Y-m-d', $start),
date('Y-m-d', strtotime('next tuesday', $start)),
date('Y-m-d', strtotime('next wednesday', $start)),
date('Y-m-d', strtotime('next thursday', $start)),
date('Y-m-d', strtotime('next friday', $start)),
date('Y-m-d', strtotime('next saturday', $start)),
date('Y-m-d', strtotime('next sunday', $start)))
;
return $week_start_end;
}
static function weekDayName($date) {
$week = Common_Datetime::week_range($date);
$key = array_search($date, $week);
$daynames = array('monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday');
$weekday = $daynames[$key];
return $weekday;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment