Relative Time in PHP [duplicate] - php

This question already has answers here:
Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...
(32 answers)
Closed 8 years ago.
I have two dates variable in php
$var1 and $var2
var1 contains some past time and var2 contains current time.I want to calculate the relative time such as 3 hrs ago,5 day ago etc
I have been stucked in this from quite a while.can anyone pls help
I already referred to the existing stackoverflow posts regarding this but it didn't help me.

you can calculate difference and then convert to natural language. And try to use Search field on StackOverflow next time ;)

Here's a function I wrote a while back to do exactly that:
function relative_date($timestamp) {
// calculate time difference
$timediff = time() - $timestamp;
switch($timediff) {
// less than a minute, show seconds
case $timediff <= 60:
$seconds = $timediff;
$str = $timediff . ($timediff == 1 ? " second ago" : " seconds ago");
break;
// less than a hour, show minutes
case $timediff <= 3600:
$minutes = floor($timediff / 60);
$str = $minutes . ($minutes == 1 ? " minute ago" : " minutes ago");
break;
// less than a day, show hours
case $timediff <= 86400:
$hours = floor($timediff / 3600);
$str = $hours . ($hours == 1 ? " hour ago" : " hours ago");
break;
// less than a year, show days
case $timediff <= (86400 * 365):
$days = floor($timediff / 86400);
$str = $days . ($days == 1 ? " day ago" : " days ago");
break;
// over a year, just show years
default:
$years = floor($timediff / (86400 * 365));
$str = $years . ($years == 1 ? " year ago" : " years ago");
}
return $str;
}

Related

Convert Days to Year,Month,Day Format

I have this problem. Can someone help me,how to convert number of days into the format XX Years, XX Month, XX Days...
i created this function,
function convert($sum) {
$years = ($sum / 365) ;
$years = floor($years);
$month = ($sum % 365) / 30.5;
$month = floor($month);
$days = ($sum % 365) % 30.5; // the rest of days
// Echo all information set
echo 'DAYS RECEIVE : '.$sum.' days<br>';
echo $years.' years - '.$month.' month - '.$days.' days';
}
convert(151);
But with 151 days the result was wrong
DAYS RECEIVE : 151 days0 years - 4 month - 1 days
it must be 4 month ans 28 days not 1 day...
http://sandbox.onlinephpfunctions.com/code/f5e6b4b4f6a27024b66ffbf04e80698722a3ecab
If you use more modern PHP, the following is based around actual days in each month:
$days = 151;
$start_date = new DateTime();
$end_date = (new $start_date)->add(new DateInterval("P{$days}D") );
$dd = date_diff($start_date,$end_date);
echo $dd->y." years ".$dd->m." months ".$dd->d." days";
Note that it will vary, depending on the current date, so you might prefer to set $start_date and $end_date to work from a fixed baseline
$days = 151;
$start_date = new DateTime('1970-01-01');
$end_date = (new DateTime('1970-01-01'))->add(new DateInterval("P{$days}D") );
$dd = date_diff($start_date,$end_date);
echo $dd->y." years ".$dd->m." months ".$dd->d." days";
This is the solution for your problem:
function convert($sum) {
$years = floor($sum / 365);
$months = floor(($sum - ($years * 365))/30.5);
$days = ($sum - ($years * 365) - ($months * 30.5));
echo “Days received: ” . $sum . “ days <br />”;
echo $years . “ years, “ . $months . “months, “ . $days . “days”;
}

PHP difference between date and today (Show weeks)

Ok, here is my problem. Instead of measuring 7 days in seconds, I want to count how many weeks (Sunday Through Saturday) there are from date #1 to today.
PHP
$today1 = date("Y-m-d");
$diff = strtotime($date1,0) - strtotime($today1,0);
echo (floor($diff / 604800));
If you're counting in seconds, why use date() when you can use time() instead- it gives out the numeric time signature of your current time, making calculations such as this much easier.
Using seconds is fine, perhaps try something like this:
$date1 = "2012-12-25";
$today1 = time();
$diff = strtotime($date1) - $today1;
if($diff < 604800) {
$week = "this week";
} else {
$week = (floor($diff / 604800) == 1)
? floor($diff / 604800) . " week away" : floor($diff / 604800) . " weeks away";
}
echo $week;

Is there something built into PHP to convert seconds to days, hours, mins?

For example if I have:
$seconds = 3744000; // i want to output: 43 days, 8 hours, 0 minutes
Do I have to create a function to convert this? Or does PHP already have something built in to do this like date()?
function secondsToWords($seconds)
{
$ret = "";
/*** get the days ***/
$days = intval(intval($seconds) / (3600*24));
if($days> 0)
{
$ret .= "$days days ";
}
/*** get the hours ***/
$hours = (intval($seconds) / 3600) % 24;
if($hours > 0)
{
$ret .= "$hours hours ";
}
/*** get the minutes ***/
$minutes = (intval($seconds) / 60) % 60;
if($minutes > 0)
{
$ret .= "$minutes minutes ";
}
/*** get the seconds ***/
$seconds = intval($seconds) % 60;
if ($seconds > 0) {
$ret .= "$seconds seconds";
}
return $ret;
}
print secondsToWords(3744000);
This is very simple and easy to find days , hours, minute and second in core php :
$dbDate = strtotime("".$yourdbtime."");
$endDate = time();
$diff = $endDate - $dbDate;
$days = floor($diff/86400);
$hours = floor(($diff-$days*86400)/(60 * 60));
$min = floor(($diff-($days*86400+$hours*3600))/60);
$second = $diff - ($days*86400+$hours*3600+$min*60);
if($days > 0) echo $days." Days ago";
elseif($hours > 0) echo $hours." Hours ago";
elseif($min > 0) echo $min." Minutes ago";
else echo "Just now";
An easy way to accomplish this nowadays is using DateTimeImmutable, DateInterval and PHP 5.5.0 or higher:
$seconds = 3744000;
$interval = new DateInterval("PT{$seconds}S");
$now = new DateTimeImmutable('now', new DateTimeZone('utc'));
$difference = $now->diff($now->add($interval))->format('%a days, %h hours, %i minutes');
The result will be:
43 days, 8 hours, 0 minutes
The code adds the seconds to a date and calculates the difference to it. Like this, the seconds are transformed into the specified days, hours and minutes.
Warning 1: Working without UTC - Clock changes
You may not specify the DateTimeZone in the constructor of the DateTimeImmutable object to UTC.
$now = new DateTimeImmutable();
There are regions in this world, where the clock changes on specific days of the year. Most countries in the EU change between a summer- and winter-time for example.
If your date interval overlaps the day on that a clock change occurs and your server is set to the related region for that clock change, the result might change as well. This is best shown with the following example:
$twentyFourHours = new DateInterval('PT24H');
$twentyFiveHours = new DateInterval('PT25H');
//Pacific time changed from summer- to winter-time on that day
$summerToWinter = new DateTimeImmutable('2018-11-04');
If you add 24 hours to the $summerToWinter date, you will get the following result:
$extra24Hours = $summerToWinter->add($twentyFourHours);
echo $summerToWinter->format('y-m-d H:i');
echo $extra24Hours->format('y-m-d H:i');
echo $summerToWinter->diff($extra24Hours)->format('%a days, %h hours, %i minutes');
18-11-04 00:00
18-11-04 23:00
0 days, 24 hours, 0 minutes
As you can see, between 00:00 and 23:00 on that day lay 24 hours, which is technically correct. Because of the clock change the timelap between 02:00 and 03:00 occured twice on that day.
Adding 25 hours will result in this:
$extra25Hours = $summerToWinter->add($twentyFiveHours);
echo $summerToWinter->format('y-m-d H:i');
echo $extra25Hours->format('y-m-d H:i');
echo $summerToWinter->diff($extra25Hours)->format('%a days, %h hours, %i minutes');
18-11-04 00:00
18-11-05 00:00
1 days, 0 hours, 0 minutes
As we can see, 1 day elapsed, that has had 25 hours. If this is applied for the 3744000 seconds from the original question, the result would show:
43 days, 7 hours, 0 minutes
The information, that an elapsed day has had 25 hours, is not shown though.
Also, I was not able to recreate the same effect for a day that changes the clock from winter to summer time, that should only elapse 23 hours.
Warning 2: Working with the raw DateInterval object
Using this code without DateTimeImmutable will cause the wrong output:
$seconds = 3744000;
$interval = new DateInterval("PT{$seconds}S");
$difference = $interval->format('%a days, %h hours, %i minutes, %s seconds');
Now, only the seconds are set in the DateInterval object. $difference would be:
(unknown) days, 0 hours, 0 minutes, 3744000 seconds
I like Ian Gregory's answer the most and upvoted it but thought i'd just simplify it a little bit :
function secondsToWords($seconds)
{
$days = intval(intval($seconds) / (3600*24));
$hours = (intval($seconds) / 3600) % 24;
$minutes = (intval($seconds) / 60) % 60;
$seconds = intval($seconds) % 60;
$days = $days ? $days . ' days' : '';
$hours = $hours ? $hours . ' hours' : '';
$minutes = $minutes ? $minutes . ' minutes' : '';
$seconds = $seconds ? $seconds . ' seconds' : '';
return $days . $hours . $minutes . $seconds;
}

PHP time conversion

Is there a PHP library that will convert a unix timestamp into something like this format:
8 hours and 17 minutes ago
I made my own script a while back that did this, I just can't track it down and would rather not spend the time recreating it (plus I think it could have been done far more efficiently).
My original code was something along the lines of:
$seconds = time() - $timestamp;
$minutes = 0;
$hours = 0;
$days = 0;
$weeks = 0;
$months = 0;
$years = 0;
while($seconds >= 60)
{
$seconds -= 60;
$minutes ++;
if($minutes >= 60)
{
$minutes -= 60;
$hours ++;
if($hours >= 24)
{
// etc
}
}
}
if($hours < 1) return "$minutes minute" . ($minutes == 1 ? "" : "s")) . " and $seconds seconds" . ($seconds == 1 ? "" : "s"));
if($minutes < 1) return "$seconds second" . ($seconds == 1 ? "" : "s"));
// etc
Better yet, if there's a nicer way to approach the above I'll give it a crack myself as well.
Yes, check The DateTime class.
$datetime1= new DateTime();
$datetime2= new DateTime();
$datetime2->setTimestamp($timestamp);
$interval = $datetime2->diff($datetime1);
echo $interval->format('%a days %h hours and %i minutes ago');
function TimeAgo($datefrom,$dateto=-1)
{
// Defaults and assume if 0 is passed in that
// its an error rather than the epoch
if($datefrom<=0) { return "A long time ago"; }
if($dateto==-1) { $dateto = time(); }
// Calculate the difference in seconds betweeen
// the two timestamps
$difference = $dateto - $datefrom;
// If difference is less than 60 seconds,
// seconds is a good interval of choice
if($difference < 60)
{
$interval = "s";
}
// If difference is between 60 seconds and
// 60 minutes, minutes is a good interval
elseif($difference >= 60 && $difference<60*60)
{
$interval = "n";
}
// If difference is between 1 hour and 24 hours
// hours is a good interval
elseif($difference >= 60*60 && $difference<60*60*24)
{
$interval = "h";
}
// If difference is between 1 day and 7 days
// days is a good interval
elseif($difference >= 60*60*24 && $difference<60*60*24*7)
{
$interval = "d";
}
// If difference is between 1 week and 30 days
// weeks is a good interval
elseif($difference >= 60*60*24*7 && $difference <
60*60*24*30)
{
$interval = "ww";
}
// If difference is between 30 days and 365 days
// months is a good interval, again, the same thing
// applies, if the 29th February happens to exist
// between your 2 dates, the function will return
// the 'incorrect' value for a day
elseif($difference >= 60*60*24*30 && $difference <
60*60*24*365)
{
$interval = "m";
}
// If difference is greater than or equal to 365
// days, return year. This will be incorrect if
// for example, you call the function on the 28th April
// 2008 passing in 29th April 2007. It will return
// 1 year ago when in actual fact (yawn!) not quite
// a year has gone by
elseif($difference >= 60*60*24*365)
{
$interval = "y";
}
// Based on the interval, determine the
// number of units between the two dates
// From this point on, you would be hard
// pushed telling the difference between
// this function and DateDiff. If the $datediff
// returned is 1, be sure to return the singular
// of the unit, e.g. 'day' rather 'days'
switch($interval)
{
case "m":
$months_difference = floor($difference / 60 / 60 / 24 /
29);
while (mktime(date("H", $datefrom), date("i", $datefrom),
date("s", $datefrom), date("n", $datefrom)+($months_difference),
date("j", $dateto), date("Y", $datefrom)) < $dateto)
{
$months_difference++;
}
$datediff = $months_difference;
// We need this in here because it is possible
// to have an 'm' interval and a months
// difference of 12 because we are using 29 days
// in a month
if($datediff==12)
{
$datediff--;
}
$res = ($datediff==1) ? "$datediff month ago" : "$datediff
months ago";
break;
case "y":
$datediff = floor($difference / 60 / 60 / 24 / 365);
$res = ($datediff==1) ? "$datediff year ago" : "$datediff
years ago";
break;
case "d":
$datediff = floor($difference / 60 / 60 / 24);
$res = ($datediff==1) ? "$datediff day ago" : "$datediff
days ago";
break;
case "ww":
$datediff = floor($difference / 60 / 60 / 24 / 7);
$res = ($datediff==1) ? "$datediff week ago" : "$datediff
weeks ago";
break;
case "h":
$datediff = floor($difference / 60 / 60);
$res = ($datediff==1) ? "$datediff hour ago" : "$datediff
hours ago";
break;
case "n":
$datediff = floor($difference / 60);
$res = ($datediff==1) ? "$datediff minute ago" :
"$datediff minutes ago";
break;
case "s":
$datediff = $difference;
$res = ($datediff==1) ? "$datediff second ago" :
"$datediff seconds ago";
break;
}
return $res;
}
/*
Input parameter is the UNIX timestamp
of the starting date.
The second parameter is optional -
It's value is the ending date,
also UNIX timestamp. If this
parameter is not given, the
default date is current date.
*/
function duration($start,$end=null) {
$end = is_null($end) ? time() : $end;
$seconds = $end - $start;
$days = floor($seconds/60/60/24);
$hours = $seconds/60/60%24;
$mins = $seconds/60%60;
$secs = $seconds%60;
$duration='';
if($days>0) $duration .= "$days days ";
if($hours>0) $duration .= "$hours hours ";
if($mins>0) $duration .= "$mins minutes ";
if($secs>0) $duration .= "$secs seconds ";
//$duration = trim($duration);
if($duration=='') $duration = '0 seconds';
return $duration;
}
It it not suits you better use some classes, given below
http://www.phpclasses.org/browse/file/6330.html

Use PHP to truncate the age of a MySQL entry to the nearest unit of time

I have a table with a datetime field, and I want to pull that time stamp and use PHP to convert it to the nearest largest unit of time. For example, if the entry was made 2 minutes and 36 seconds ago, I want to echo 2 minutes in PHP. If it was 3 hours and 5 minutes ago, I want it to say 3 hours. If it was 6 days and 4 hours and 40 minutes ago, it should say 6 days. You get my drift. And if it's under a minute, just the number of seconds.
I am not familiar at all about any of PHP's date or time functions, so please don't assume I already know anything. Thanks.
Here's another function for you:
function relativeTime($timestamp, $format = "Y-m-d")
{
$difference = time() - $timestamp;
if ($difference >= 604800) { // 7 days
return date($format, $timestamp);
}
$periods = array("Second", "Minute", "Hour", "Day");
$lengths = array("60","60","24","7","4.35","12","10");
$ending = "Ago";
for($j = 0; $difference >= $lengths[$j]; $j++)
$difference /= $lengths[$j];
$difference = round($difference);
if($difference != 1) $periods[$j].= "s";
$text = "$difference $periods[$j] $ending";
return $text;
}
It returns values like "5 Minutes Ago", "3 Days Ago", and "34 Seconds Ago". However if the date is over 7 days old, it just returns the full date, i.e. "2010-04-19".
If your field is date or datetime use
SELECT UNIX_TIMESTAMP(field) FROM...
if your field is stored as an int (seconds since 1970) just use
SELECT field FROM...
Get that integer value from the database into a PHP variable $secs, this is the number of seconds since 1970. We assume the date is in the past, then
$diff = time() - $secs;
if ($diff < 60) echo $diff . ' seconds';
else {
$diff = intval($diff / 60);
if ($diff < 60) echo $diff . ' minutes';
else {
$diff = intval($diff / 60);
if ($diff < 24) echo $diff . ' hours';
else {
$diff = intval($diff / 24);
echo $diff . ' days';
}
}
}

Categories