Tuesday, May 1

PEAR Date compare()

Alright. I've got this figured out. I'm not sure if this is exactly how you're supposed to do stuff, being new to PEAR as I am, but this seems to work.

The problem:
I have due dates stored in a database. On the webpage, I want to say the due date, then say how many days until the due date (or how many days have passed since the due date.

The code:

We start of creating two date objects, one from the database, one for today.

$due = new Date($row['due_date']);
$d = new Date();
so now we want to compare them. PEAR has a cute little compare function for us. It returns 0 if the dates are equal, -1 if date1 is before date2 and 1 if date1 is after date2.
$comp = Date::compare($due, $d);
So now, we'll get 0, -1 or 1 and we need to handle them. And I want to find out how many days till the project is due.
if($comp == '1'){
$x = Date_Calc::dateToDays($due->day, $due->month, $due->year) - Date_Calc::dateToDays($d->day, $d->month, $d->year);
$daysleft = $x.' days left';
}elseif($comp == -1){
$x = Date_Calc::dateToDays($d->day, $d->month, $d->year) - Date_Calc::dateToDays($due->day, $due->month, $due->year);
$daysleft = $x.' days overdue';
}else $daysleft = 'today';
So the Date_Calc::dateToDays returns a number. It's the number of days since the Date_Calc epoch. It doesn't really matter what it is, it gives us a constant to work with. Just subtracting them returns the number of days. So my page really just says:
<strong>Date Due:</strong> <?=$due->format('%A, %B %e, %Y')?> (<?=$daysleft?>)
and displays:

Date Due: Friday, June 15, 2007 (43 days left)

No comments: