PHP date and time functions

Date difference

Calculate the difference between two dates for a given unit (days, months, seconds, …)

// note: this function is not ment to copy-paste to your project. // Performance is not good. You should only use the code-parts that you really need.
 
function date_difference($date_1 , $date_2 , $unit) {   $datetime1 = date_create($date_1);   $datetime2 = date_create($date_2);    $interval = date_diff($datetime1, $datetime2);   $days  = $interval->days;   $years = $interval->format('%y');    $addMonths  = $interval->format('%m');   $addDays    = $interval->format('%d');   $addHours   = $interval->format('%h');   $addMinutes = $interval->format('%i');   $addSeconds = $interval->format('%s');    switch($unit) {     case 'weeks':       return $days / 7;     case 'seconds':       return $days * 86400 + $addHours * 3600 + $addMinutes * 60 + $addSeconds;     case 'minutes':       return $days * 1440 + $addHours * 60 + $addMinutes;     case 'hours':       return $days * 24 + $addHours;     case 'days':       return $days + $addHours / 24;     case 'months':       return $years * 12 + $addMonths + $addDays / 30; // hmm...     case 'years':       return $years + $addMonths / 12 + $addDays / 365.24219; // ;-)   }
  // something went wrong
  return false;
}

Date ranges for the last year

Get the monthly date ranges for one year starting from the last complete month.

function getDateRangesForLastYear() {   $format = 'Y-m-d';   $numberOfMonths = 12;   $ranges = [];   while ($numberOfMonths > 0) {     $monthStart = mktime(0, 0, 0, date('m')-$numberOfMonths, 1, date('Y'));     $monthEnd = mktime(0, 0, 0, date('m')-$numberOfMonths+1, date('d') - 1, date('Y'));     $numberOfMonths--;     $ranges[] = [date($format, $monthStart), date($format, $monthEnd)];   }   return $ranges;
}
Feedback
Wir bearbeiten Dein Feedback aus diesem Formular über gitlab.com – Du kannst das E-Mail Feld leer lassen, falls Du keine Antwort von uns erwartest. Alternative Kontaktmöglichkeiten findest Du im Impressum.