Jump to content

Approximate date


tail

Recommended Posts

I'm currently using a function to change my dates to more a more readable format such as "3 hours ago" or "9 months ago". However, if the date given is 9 months and one week ago, it will only output "9 months ago". Can someone help me edit the function I'm using? Here's the function I'm currently using:

function nicetime($date)

{

	if(empty($date)) {

		return "No date provided";

	}

	$periods         = array("second", "minute", "hour", "day", "week", "month", "year", "decade");

	$lengths         = array("60","60","24","7","4.35","12","10");

	$now             = time();

	$unix_date         = strtotime($date);

	   // check validity of date

	if(empty($unix_date)) {   

		return "Bad date";

	}

	// is it future date or past date

	if($now > $unix_date) {   

		$difference     = $now - $unix_date;

		$tense         = "ago";						   

	} else {

		$difference     = $unix_date - $now;

		$tense         = "from now";

	}					   

	for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {

		$difference /= $lengths[$j];

	}					   

	$difference = round($difference);					   

	if($difference != 1) {

		$periods[$j].= "s";

	}					   

	return "$difference $periods[$j] {$tense}";

}

Link to comment
https://forums.phpfreaks.com/topic/180059-approximate-date/
Share on other sites

<?php
function nicetime($date){
if(empty($date)) return "No date provided";
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array("60","60","24","7","4.35","12","10");
$now = time();
$unix_date = strtotime($date);
if(empty($unix_date)) return "Bad date";
if($now > $unix_date) {   
	$difference     = $now - $unix_date;
	$tense         = "ago";						   
} else {
	$difference     = $unix_date - $now;
	$tense         = "from now";
}					   
$j = 0;
$out = array();
while ($difference>0){
	$x = $difference % $lengths[$j];
	$difference = (int) $difference / $lengths[$j];
	$s = $x > 1 ? 's' : '';
	if ($x) $out[$periods[$j].$s] = $x;
	$j++;
}
$out = array_reverse($out);				   
$out1 = '';
foreach ($out as $p => $v) $out1 .= " $v ($p)";			   
return "$out1 {$tense}";
}
echo nicetime('3-11-2009 10:22:23');
?>

Link to comment
https://forums.phpfreaks.com/topic/180059-approximate-date/#findComment-950093
Share on other sites

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.