note 104001 added to datetime.diff

From: Date: Mon, 16 May 2011 22:00:31 +0000
Subject: note 104001 added to datetime.diff
Groups: php.notes 
Request: Send a blank email to php-notes+get-179771@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. $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 ---- Server IP: 69.147.83.197 Probable Submitter: 174.127.8.233 ---- Manual Page -- http://www.php.net/manual/en/datetime.diff.php Edit -- https://master.php.net/note/edit/104001 Del: integrated -- https://master.php.net/note/delete/104001/integrated Del: useless -- https://master.php.net/note/delete/104001/useless Del: bad code -- https://master.php.net/note/delete/104001/bad+code Del: spam -- https://master.php.net/note/delete/104001/spam Del: non-english -- https://master.php.net/note/delete/104001/non-english Del: in docs -- https://master.php.net/note/delete/104001/in+docs Del: other reasons-- https://master.php.net/note/delete/104001 Reject -- https://master.php.net/note/reject/104001 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#179771) next »