note 104001 modified in datetime.diff by danbrown

From: Date: Tue, 17 May 2011 14:23:17 +0000
Subject: note 104001 modified in datetime.diff by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-179809@lists.php.net to get a copy of this message
I was looking for a way to output X number of days from a given date and didn't find exactly what I was looking for. But I got this working. I hope this helps you. This will output the number of days,months, or years difference between NOW and a April 1st, 2011. <?php $date1 = new DateTime('2011-04-01'); $date2 = new DateTime("now"); $interval = $date1->diff($date2); $years = $interval->format('%y'); $months = $interval->format('%m'); $days = $interval->format('%d'); if($years!=0){ $ago = $years.' year(s) ago'; }else{ $ago = ($months == 0 ? $days.' day(s) ago' : $months.' month(s) ago'); } echo $ago; ?> If I used today, 2011-05-16 as $date1, I could return all 0's in the format. For example.... <?php $date1 = new DateTime('2011-05-161'); $date2 = new DateTime("now"); $interval = $date1->diff($date2); $diff = $interval->format('%y-%m-%d'); echo $diff; //Today, this will output 0-0-0 ?> --was-- I was looking for a way to output X number of days from a given date and didn't find exactly what I was looking for. But I got this working. I hope this helps you. This will output the number of days,months, or years difference between NOW and a April 1st, 2011. $date1 = new DateTime('2011-04-01'); $date2 = new DateTime("now"); $interval = $date1->diff($date2); $years = $interval->format('%y'); $months = $interval->format('%m'); $days = $interval->format('%d'); if($years!=0){ $ago = $years.' year(s) ago'; }else{ $ago = ($months == 0 ? $days.' day(s) ago' : $months.' month(s) ago'); } echo $ago; If I used today, 2011-05-16 as $date1, I could return all 0's in the format. For example.... $date1 = new DateTime('2011-05-161'); $date2 = new DateTime("now"); $interval = $date1->diff($date2); $diff = $interval->format('%y-%m-%d'); echo $diff; //Today, this will output 0-0-0 http://php.net/manual/en/datetime.diff.php

« previous php.notes (#179809) next »