Jump to content

Date display help!


ShootingBlanks

Recommended Posts

Hello.  First I'll show the code I have now, then I'll explain what I want.  Here's what I have:

 

// *** Countdown Timer *** \\
$target = mktime(0, 0, 0, 9, 19, 2009);
$today = time();
$difference = ($target-$today);
$days = (int) ($difference/86400);

if ($days > 0) {
echo "<p id='countdown'>".$days." days and counting!</p>";
} elseif ($days == 0) {
echo "<p id='countdown'>IT'S TIME!!!</p>";
} else { 
echo "<p id='countdown'>It's been ".abs($days)." days!</p>";
}

 

The above code works with no problems, but I want to modify it and I'm not sure how.

 

I have a base date of September 19th, 2009.  I'm trying to display how many days it's been since that date.  Right now it only displays it as "days".  What I'd like is:

 

  • If it's the 19th of any month before September 19th, 2010, it'll just display "x months".  So if the date today were July 19th, 2010, it would display:
     
    10 months
     
  • If it's any year to the date, it'll just display "x years".  So if the date today were September 19th, 2013, it would display:
     
    4 years
     
  • If it's the 19th of any month after September 19th, 2010, it'll just display "x years and x months".  So if the date today were December 19th, 2011, it would display:
     
    2 years and 3 months
     
  • If it's more than a year after September 19th, 2009 but less than October 19th of the current year, it'll display "x years and x days".  So if the date today were October 2nd, 2010, it would display:
     
    1 year and 13 days
     
  • If it's anything else, it'll display "x years, x months, and x days".  So if the date today were October 27th, 2012, it would display:
     
    3 years, 1 month, and 8 days
     

Any help with this would be greatly appreciated, cuz I'm stumped!  Thanks!!!  :-*

Link to comment
Share on other sites

$timestamp = mktime(0, 0, 0, 9, 19, 2009);

$datetime = new DateTime();
$datetime->setTimestamp($timestamp);

$now = new DateTime();
$interval = $now->diff($datetime);

if ($interval->y && $interval->m && $interval->d) {
    echo $interval->format('%y years, %m month(s), and %d day(s)');
} else if (0 === $interval->d && ($interval->y && $interval->m)) {
    echo $interval->format('%y years and %m month(s)');
} else if (0 === $interval->m && ($interval->y && $interval->d)) {
    echo $interval->format('%y year and %d day(s)');
} else if ((0 === $interval->m && 0 === $interval->d) && $interval->y) {
    echo $interval->format('%y year(s)');
} else if ($interval->m) {
    echo $interval->format('%m month(s)');
}

Link to comment
Share on other sites

Getting closer!  Now I'm getting this error:

 

Fatal error: Call to undefined method DateTime::diff() in C:\htdocs\stacyandmatt\datetest.php  on line 10

 

Just to catch up so we're on the same page with the code still, my first 10 lines are:

 

$timestamp = mktime(0, 0, 0, 9, 19, 2009);

$datetime = new DateTime();
version_compare('5.3.0', PHP_VERSION, '>')
    ? $datetime->modify(date(DateTime::ATOM, $timestamp))
    : $datetime->setTimestamp($timestamp);

$now = new DateTime();
$interval = $now->diff($datetime);

Link to comment
Share on other sites

try:

    $diff = date('m,d,Y,h,i,s',mktime(0, 0, 0, 9, 19, 2009)-time());
    $unit = array('month','day','year','hour','minute','second');
    $diff = explode(',',$diff);
    $output = '';
    foreach($diff as $key => $time){
        if($time < 1){
            continue;
        }else if($time = 1){
            if($output != ''){
                $output .= ', '.$time.' '.$unit[$key];
            }else{
                $output .= ' '.$time.' '.$unit[$key];
            }
        }else{
            if($output != ''){
                $output .= ', '.$time.' '.$unit[$key].'s';
            }else{
                $output .= ' '.$time.' '.$unit[$key].'s';
            }
        }
    }
    $output .= ' ago';
    echo $output;

to lower the amount of things shown just take away from the date format

Link to comment
Share on other sites

I'm in a hurry.

 

Just adding to the mix, may need some more editing.

<?php

//set real dates for start and end, otherwise *nix the strtotime() lines.
//$return 'days' will return days/hours/minutes/seconds.
//$return 'hours' will return hours/minutes/seconds.
//$return 'minutes' will return minutes/seconds.
//$return 'seconds' will return seconds.
function timeDifference($start,$end,$return='decade') {
$start = strtotime($start);
$end = strtotime($end);
$difference = max($end, $start) - min($end,$start);
    $time = NULL;
    //calculate time difference.
    switch($return) {
        case 'decade':
            $decade = floor($difference/315705600);
                $difference = $difference % 315705600;
                    $time['decade'] = $decade;
        case 'year':
            $year = floor($difference/31570560);
                $difference = $difference % 31570560;
                    $time['year'] = $year;
        case 'month':
            $month = floor($difference/2630880);
                $difference = $difference % 2630880;
                    $time['month'] = $month;
        // case 'week':
            // $week = floor($difference/604800);
                // $difference = $difference % 604800;
                    // $time['week'] = $week;
        case 'days':
             $days = floor($difference/86400);
                $difference = $difference % 86400;
                    $time['day'] = $days;
        // case 'hours':
            // $hours = floor($difference/3600);
                // $difference = $difference % 3600;
                    // $time['hour'] = $hours;
        // case 'minutes':
            // $minutes = floor($difference/60);
                // $difference = $difference % 60;
                    // $time['minute'] = $minutes;
        // case 'seconds':
            // $seconds = $difference;
                // $time['second'] = $seconds;
    }   
    
       if(is_array($time)) {
		if($start > $end) {
			foreach($time as $key => $value) {
				if($value > 0) {
					if($value > 1) {
						$key = $key . 's';
					}
					return $value . ' ' . $key . ' ago.';
				}
			}
		}
		elseif($end > $start) {
			foreach($time as $key => $value) {
				if($value > 0) {
					if($value > 1) {
						$key = $key . 's';
					}
					$output .= $value . ' ' . $key . ' until.';
				}
			}
		}
        }
    return $output;
}  

$start = 'September 19th, 2009';
echo timeDifference($start,'2008-02-01 16:32:09');

?>

Link to comment
Share on other sites

heres a fix of mine

<?php
    $date = -1*(mktime(0, 0, 0, 9, 19, 2009)-time());
    $diff = date('m,d,Y,h,i,s',$date);
    $unit = array('month','day','year','hour','minute','second');
    $diff = explode(',',$diff);
    $output = '';
    foreach($diff as $key => $time){
        if($time < 1){
            continue;
        }else if($time == 1){
            if($output != ''){
                $output .= ', '.$time.' '.$unit[$key];
            }else{
                $output .= ' '.$time.' '.$unit[$key];
            }
        }else{
            if($output != ''){
                $output .= ', '.$time.' '.$unit[$key].'s';
            }else{
                $output .= ' '.$time.' '.$unit[$key].'s';
            }
        }
    }
    $output .= ' ago';
    echo $output;
?>

Link to comment
Share on other sites

jcbones -

 

Copying and pasting yours as-is returns:

 

1 year ago.

 

So I don't think that's correct.

 

ldb358 -

 

You're getting closer.  I think the days and months are correct, but the year is just off.  Right now, yours is reading:

 

07 months, 16 days, 1970 years, 02 hours, 26 minutes, 06 seconds ago

 

Sorry this is so difficult.  Are there any another suggestions?  Thanks so much!!!

 

Link to comment
Share on other sites

If you look at the dates I passed that function, then yes, 1 year ago would be the correct answer for what you are asking according to your first post.

 

Try putting in the dates that YOU want to check.

 

<?php

//set real dates for start and end, otherwise *nix the strtotime() lines.
//$return 'days' will return days/hours/minutes/seconds.
//$return 'hours' will return hours/minutes/seconds.
//$return 'minutes' will return minutes/seconds.
//$return 'seconds' will return seconds.
function timeDifference($start,$end,$return='decade') {
$start = strtotime($start);
$end = strtotime($end);
$difference = max($end, $start) - min($end,$start);
    $time = NULL;
    //calculate time difference.
    switch($return) {
        case 'decade':
            $decade = floor($difference/315705600);
                $difference = $difference % 315705600;
                    $time['decade'] = $decade;
        case 'year':
            $year = floor($difference/31570560);
                $difference = $difference % 31570560;
                    $time['year'] = $year;
        case 'month':
            $month = floor($difference/2630880);
                $difference = $difference % 2630880;
                    $time['month'] = $month;
        // case 'week':
            // $week = floor($difference/604800);
                // $difference = $difference % 604800;
                    // $time['week'] = $week;
        case 'days':
             $days = floor($difference/86400);
                $difference = $difference % 86400;
                    $time['day'] = $days;
        // case 'hours':
            // $hours = floor($difference/3600);
                // $difference = $difference % 3600;
                    // $time['hour'] = $hours;
        // case 'minutes':
            // $minutes = floor($difference/60);
                // $difference = $difference % 60;
                    // $time['minute'] = $minutes;
        // case 'seconds':
            // $seconds = $difference;
                // $time['second'] = $seconds;
    }   
    
       if(is_array($time)) {
		if($start > $end) {
			foreach($time as $key => $value) {
				if($value > 0) {
					if($value > 1) {
						$key = $key . 's';
					}
					return $value . ' ' . $key . ' ';
				}
			}
		}
		elseif($end > $start) {
			foreach($time as $key => $value) {
				if($value > 0) {
					if($value > 1) {
						$key = $key . 's';
					}
					@$output .= $value . ' ' . $key . ' ';
				}
			}
		}
        }
    return $output;
}  

$start = 'September 19th, 2009';
echo timeDifference($start,date('Y-m-d'));

?>

 

September 9 2009 until now = 6 months 14 days

 

<?php

//set real dates for start and end, otherwise *nix the strtotime() lines.
//$return 'days' will return days/hours/minutes/seconds.
//$return 'hours' will return hours/minutes/seconds.
//$return 'minutes' will return minutes/seconds.
//$return 'seconds' will return seconds.
function timeDifference($start,$end,$return='decade') {
$start = strtotime($start);
$end = strtotime($end);
$difference = max($end, $start) - min($end,$start);
    $time = NULL;
    //calculate time difference.
    switch($return) {
        case 'decade':
            $decade = floor($difference/315705600);
                $difference = $difference % 315705600;
                    $time['decade'] = $decade;
        case 'year':
            $year = floor($difference/31570560);
                $difference = $difference % 31570560;
                    $time['year'] = $year;
        case 'month':
            $month = floor($difference/2630880);
                $difference = $difference % 2630880;
                    $time['month'] = $month;
        case 'week':
            $week = floor($difference/604800);
                $difference = $difference % 604800;
                    $time['week'] = $week;
        case 'days':
             $days = floor($difference/86400);
                $difference = $difference % 86400;
                    $time['day'] = $days;
        case 'hours':
            $hours = floor($difference/3600);
                $difference = $difference % 3600;
                    $time['hour'] = $hours;
        case 'minutes':
            $minutes = floor($difference/60);
                $difference = $difference % 60;
                    $time['minute'] = $minutes;
        case 'seconds':
            $seconds = $difference;
                $time['second'] = $seconds;
    }   
    
       if(is_array($time)) {
		if($start > $end) {
			foreach($time as $key => $value) {
				if($value > 0) {
					if($value > 1) {
						$key = $key . 's';
					}
					return $value . ' ' . $key . ' ';
				}
			}
		}
		elseif($end > $start) {
			foreach($time as $key => $value) {
				if($value > 0) {
					if($value > 1) {
						$key = $key . 's';
					}
					@$output .= $value . ' ' . $key . ' ';
				}
			}
		}
        }
    return $output;
}  

$start = 'September 19th, 2009';
echo timeDifference($start,date('Y-m-d H:i:s'));

?>

 

Same code with sections un-commented.

 

6 months 2 weeks 3 hours 48 minutes 55 seconds

 

 

?>

 

[/code]

 

 

Link to comment
Share on other sites

Try putting in the dates that YOU want to check.

 

I guess that's where I'm unclear (and sorry for being such a novice about this, so my questions may be not so smart).  But I'm not sure how to plug in the date I want to check.  The date I want to check is whatever the current date is (so, that would change daily).  Let me know if my original post was unclear, maybe.  What I posted initially is exactly what I'm looking for.  It sounds like your code will do it...I'm just not competent enough to modify it to work properly for me.

 

Thanks!!!

Link to comment
Share on other sites

At the bottom of the script, change the value of $start.  It will do the rest.

 

Sorry about that - I just saw that.  One more problem, though...

 

...When I change it to the current date, I'm now getting:

 

6 months 13 days

 

You say you're getting:

 

6 months 14 days

 

But either way, it's really been 6 months and 15 days (the 19th of March to the 3rd of April is 15 days).  Why is my readout different than yours, and how can I adjust it even one day further from that so that it is truly accurate?

 

Thanks so much!!!

 

Link to comment
Share on other sites

date('m,d,Y,h,i,s',mktime(0, 0, 0, 9, 19, 2009)-time());

-1*(mktime(0, 0, 0, 9, 19, 2009)-time());

 

Makes no sense at all in the first case you subtract the current timestamp from a timestamp in the past (leading to a negative number) then the second you compensate that by multiplying it with -1 (which translates to abs(mktime(0, 0, 0, 9, 19, 2009) - time()))

 

If you wanted the delta why not just: time() - mktime(0, 0, 0, 9, 19, 2009)?

Link to comment
Share on other sites

At the top of the script:

 

$timezone = 'America/Los_Angeles';  //Change to your timezone.
date_default_timezone_set($timezone);

 

Timezones accepted. http://www.php.net/manual/en/timezones.php

 

I changed it to mine ('America/Chicago'), but that didn't affect anything.  I've just resorted to using September 17th (instead of September 19th), as the 2-day variance seems to work itself out...

 

What I also found odd (when testing and playing with the code) is that as soon as you bring a "year" into it (right now it hasn't been a year yet, so it's only "months" and "days") then it goes off ANOTHER day (for a total of three days).  So as soon as we hit September 19th 2010, I'll have to change the script's starting date from September 17th 2009 to September 16th 2009 (in order to have it REFLECT September 19th 2009).  Odd, but as long as it works that' fine with me.  Thanks, jcbones!

Link to comment
Share on other sites

The reason you are seeing this difference, is the function sets a months time as 30 and one-half days.  So, it only returns a close approx. amount of time.  I will get the function dead accurate just for you.  Give me a second.

Link to comment
Share on other sites

Try this, and pay attention to the note above $start, as any other format will not work.

 

<?php

//set real dates for start and end, otherwise *nix the strtotime() lines.
//$return 'days' will return days/hours/minutes/seconds.
//$return 'hours' will return hours/minutes/seconds.
//$return 'minutes' will return minutes/seconds.
//$return 'seconds' will return seconds.
function timeDifference($start,$end,$return='decade') {
$ex = explode('-',$start);
$m = ($ex[1] < 10) ? (int)substr($ex[1],1,1) : (int)$ex[1];
$y = (int)$ex[0];

$months = array(1 => 2678400, 2=>2419200, 3=>2678400, 4=>2592000, 5=>2678400, 6=>2592000, 7=>2678400,
				8=>2678400, 9=>2592000, 10=>2678400, 11=>2592000, 12=>2678400);
$lyears = array(2000,2004,2008,2012,2016,2020,2024,2028,2032,2036,2040,
					2044,2048,2052,2056,2060,2064,2068,2072,2076,2080,2084,
					2088,2092,2096);

$start = strtotime($start);
$end = strtotime($end);
$difference = max($end, $start) - min($end,$start);	
    $time = NULL;
    //calculate time difference.
   switch($return) {
	case 'decade':
		$dy = $y;
		$decade = NULL;
		for($i = 1; $i <= 10; $i++) {
			@$dyear += (in_array($dy,$lyears)) ? 31622400 : 31536000;
			++$dy;
		}
	    $decade = floor($difference/$dyear);
                $difference = $difference % $dyear;
                    $time['decade'] = $decade;
	case 'year':
		$ty = $y;
		$tm = $m;
		$year = NULL;
		while($difference >= 31536000) {
			@$tyear = (in_array($ty,$lyears)) ? 31622400 : 31536000;
			if($difference >= $tyear) {
				@$year++;
				$difference = $difference - $tyear;
			}
			++$ty;
		}				
                    $time['year'] = $year;
	case 'month':			
		$month = NULL;
		while($difference > 2419200 || (!in_array($y,$lyears) && $m == 2 && $difference == 2419200)) {
			if(in_array($y,$lyears, true) && $m === 2) {
				@$month += ($difference >= 2505600) ? 1 : 0;
				$difference = $difference - 2505600;					
			}
			else {
				@$month += ($difference >= $months[$m]) ? 1 : 0;
				$difference = $difference - $months[$m];				
			}
			$y = ($m == 12) ? ++$y : $y;
			$m = ($m == 12) ? 1 : ++$m;
		}               
                    $time['month'] = $month;					
	case 'week':
		$week = floor($difference/604800);
                $difference = $difference % 604800;
                    $time['week'] = $week;
	case 'days':
		$days = floor($difference/86400);
                $difference = $difference % 86400;
                    $time['day'] = $days;
	case 'hours':
		$hours = floor($difference/3600);
                $difference = $difference % 3600;
                    $time['hour'] = $hours;
	case 'minutes':
		$minutes = floor($difference/60);
                $difference = $difference % 60;
                    $time['minute'] = $minutes;
	case 'seconds':
        $seconds = $difference;
                $time['second'] = $seconds;
    }   
    
       if(is_array($time)) {
		if($start > $end) {
			foreach($time as $key => $value) {
				if($value > 0) {
					if($value > 1) {
						$key = $key . 's';
					}
					return $value . ' ' . $key . ' ';
				}
			}
		}
		elseif($end > $start) {
			foreach($time as $key => $value) {
				if($value > 0) {
					if($value > 1) {
						$key = $key . 's';
					}
					@$output .= $value . ' ' . $key . ' ';
				}
			}
		}
        }
    return $output;
}  

//Time MUST be in format YYYY-MM-DD (optional) H:M:S (hours:minutes:seconds);
$start = '2009-09-19';
echo timeDifference($start,date('Y-m-d H:i:s'));

?>

Link to comment
Share on other sites

Try this, and pay attention to the note above $start, as any other format will not work.

 

That worked awesome!  Thanks so much for the detailed reply and for all the work!!!

 

It's still doing the weird thing where if you change it to more than a year back (like, switch it to 2008-09-19 instead of 2009-09-19) then it will knock off a day.  But I figure after a year I'll just manually adjust the code (unless you have a solution).  Thanks!

Link to comment
Share on other sites

Moving back a year makes it count the leap year, so dropping a day is correct.  As the extra day is counted in the leap year.  The only problem I'm encountering right now, is it is losing 1 hour, if the start date is in a certain range.  Although I understand your mistake on this one, as I tried 4 hours to get it to quit dropping the day.  Then I got a calendar out, and started counting it up.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.