Wrote this PHP date function which can easily be used to populate a drop down in a form.
e.g. credit card expiry, or date of birth.
function getDateYears( $start = NULL, $before = NULL, $after = NULL, $sort = NULL ) {
if ( empty( $start ) || ( empty( $before ) && empty( $after ) ) ) {
return false;
}
$years = array( $start );
if ( $before ) {
for( $i = 1; $i <= $before; $i++ ) {
$years[] = $start - $i;
}
}
if ( $after ) {
for( $i = 1; $i <= $after; $i++ ) {
$years[] = $start + $i;
}
}
asort( $years );
if ( $sort ) {
rsort( $years );
}
return $years;
}
Example usage:
// The next 10 years, starting with the current year.
getDateYears( date('Y'), 0, 10 );
// 10 years either side of 1982, and sort in reverse.
getDateYears( 1982, 10, 10, TRUE );
What about months? It would be more efficient to have this as a static array, but where’s the fun in that. You get month number (with leading zeros) as the key, and the value is the full month (December). Perfect for insertion into a date field in MySQL.
function getDateMonths() {
$months = array();
for( $i = 1; $i <= 12; $i++ ) {
$months[str_pad( $i, 2, '0', STR_PAD_LEFT )] = date( 'F', mktime( 0, 0, 0, $i, 1 ) );
}
return $months;
}
If you found this article useful, help me out by leaving a comment below and clicking the Like button.