Jump to content

[SOLVED] Simple noob question: How to get days elapsed?


paschim

Recommended Posts

<?php
$start = strtotime('5/21/1988'); // Start time, for instance, my birthday!
$end = time(); // End time, today.

$sDate = date('n/j/Y', $start);
$eDate = date('n/j/Y', $end);
list($eMonth, $eDay, $eYear) = explode('/', $eDate);
list($sMonth, $sDay, $sYear) = explode('/', $sDate);

$yearDiff = $eYear - $sYear;
$monthDiff = $eMonth - $sMonth;
$dayDiff = $eDay - $sDay;

if($dayDiff < 0) {
--$monthDiff;
$dayDiff = date('t', $sMonth) - $sDay + $eDay;
}

if($monthDiff < 0) {
--$yearDiff;
$monthDiff += 12;
}

echo "$yearDiff years $monthDiff months $dayDiff days";
?>

 

It's accurate to the day, if you want hours/minutes/seconds... go for it! Also, this could be a little more efficient (less repeated code, etc) but I didn't do that to keep it simple so it's easy for you to read :D if you want to break it up into functions, go for it.

 

EDIT: just a sec, messed something up :) let me fix it.

Another EDIT: okay, fixed the date calculation, it's 3 am, give me a break :D

Okay, you wanted month/year, right? here you go.

 

<?php
$start = strtotime('2/28/1988'); // Start time, for instance, my birthday!
$end = strtotime('6/27/2008'); // End time, today.

$sDate = date('n/j/Y', $start);
$eDate = date('n/j/Y', $end);
list($eMonth, $eDay, $eYear) = explode('/', $eDate);
list($sMonth, $sDay, $sYear) = explode('/', $sDate);

$yearDiff = $eYear - $sYear;
$monthDiff = $eMonth - $sMonth;
$dayDiff = $eDay - $sDay;

if($dayDiff < 0) {
--$monthDiff;
}

if($monthDiff < 0) {
--$yearDiff;
$monthDiff += 12;
}

echo "$yearDiff years $monthDiff months";

 

doesn't work for day, but hey, you didn't say you wanted that working...

 

tell me when it isn't 3:30 am if you want me to fix it, it's just annoying because of the difference in numbers of days/month I'd have to rewrite half of it to get it working correctly :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.