sql while functions - php

function timeago($ptime) {
$etime = time() - $ptime;
if ($etime < 1) {
return '0 seconds';
}
$a = array( 12 * 30 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($a as $secs => $str) {
$d = $etime / $secs;
if ($d >= 1) {
$r = round($d);
return $r . ' ' . $str . ($r > 1 ? 's' : '');
}
}
}
lets say i have that function, and i have an sql result that give me an array with multiple time stamps in UNIX form. using a while loop, how can i use this function for each timestamp so each loop result would contain the time ago of each sql UNIX timestamp?

You could use DateTime class.
function timeAgo($ptime){
$date1 = DateTime::createFromFormat("s", $ptime);//HOPE THIS WILL WORK
$date2 = new DateTime("now");
$interval = $date1->diff($date2);
$diff = $interval->format('%y-%m-%d');
return $diff;
}
invoke this method on each iteration and pass in the timestamp from the DB.

Related

Get difference between two timestamps in minutes, hours or seconds in php

I have two timestamps and i would lime to get the difference based on
if its more that 60 seconds get in minutes
If more than 60 min get difference in hours
In my code i have
$diff = ($truckHistory->created_at - $model->created_at);
return $diff
The above returns in seconds
SO i have tried
$diff = ($truckHistory->created_at - $model->created_at);
return $this->convertToSecMinHour($diff)
public function convertToSecMinHour($diff){
switch($diff){
case ($diff <= 60):{
return $diff. "sec"
break;
}
//stuck for minutes and hours cases
}
}
I have this function that does just that, but it includes other methods of gauging time. You can simply remove those you do not need.
public function timeAgo($timestamp) {
$estimateTime = time() - $timestamp;
if ($estimateTime < 1) {
return 'less than 1 second ago';
}
$condition = array(
12 * 30 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($condition as $secs => $str) {
$d = $estimateTime / $secs;
if($d >= 1) {
$r = round( $d );
return $r . ' ' . $str . ( $r > 1 ? 's' : '' ) . ' ago';
}
}
}
You can get quickly using this function just passed the seconds to it. Example here
$time1 = '1504802148'; // Unix timeStamp
$timeDiff = ceil((time() - $time1));
echo secondsToTime($timeDiff);
function secondsToTime($seconds) {
$dtF = new \DateTime('#0');
$dtT = new \DateTime("#$seconds");
$makeTime = $dtF->diff($dtT)->format('%ad,%hh,%im,%ss');
$data = explode(",", $makeTime);
$array = array('0d', '0h', '0m');
$time = array_diff($data, $array);
return implode("", $time);
}
Use this function:
<?php
$diff = (time() - time()+60);
$diff2 = (time() - time()+2000);
$diff3 = (time() - time()+5000);
echo convertToSecMinHour($diff)."<br>";
echo convertToSecMinHour($diff2)."<br>";
echo convertToSecMinHour($diff3)."<br>";
function convertToSecMinHour($diff, $decimals = 2) {
switch($diff){
case ($diff <= 60):
$result = $diff;
$unit = "sec";
break;
case ($diff > 60 && $diff < 3600):
$result = ($diff / 60);
$unit = "min";
break;
case ($diff >= 3600):
$result = ($diff / (60 * 60));
$unit = "hrs";
break;
default:
$result = 0;
$unit = "";
}
return round($result, $decimals).$unit;
}
It'll return difference in seconds (i.e. 20 sec) if difference is less than 60, difference in minutes (i.e. 20 min) if difference is between 60 and 3600 seconds, and difference in hours (i.e. 20 hrs) if difference is larger than 3600. The second parameters is for number of decimals you want in the result (by default, 2).
Demo
I think you want $result and also you have other variables to use
$result;
$hour = $diff / 3600;
if ($hour == 0) {
$min = ($diff % 3600) / 60;
if ($min == 0) {
$sec = ($diff % 3600) % 60;
$result = $sec;
}else{
$result = $min;
}
}else{
$result = $hour;
}

message date ago (xx month ago or years)

Good day guys, I am having a bit trouble of how can I make this like xx month/s ago and year/s ago if the days reach the number of months/years. Is it possible ? Anyway I'm making a messaging module. This is my code. Advance thank you for your help guys
<?php
date_default_timezone_set('Asia/Manila');
$now = strtotime(date("Y-m-d H:i:s"));
$date = strtotime($key->message_date); //this is the date where message was sent
$dateDiff = abs($now - $date);
$fullDays = floor($dateDiff/(60*60*24));
if($fullDays==0)
{
echo " Today ";
}
else if($fullDays==1)
{
echo " Yesterday ";
}
else
{
echo $fullDays ." days ago";
}
$at=date('g:iA',$date)
?> at <?php echo $at?>
You can use this function you have Pass message time as an argument
function convert_time($ptime){
$etime = time() - $ptime;
if($etime < 1){
return '0 seconds';
}
$a = array( 12 * 30 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($a as $secs => $str){
$d = $etime / $secs;
if($d >= 1){
$r = round($d);
return $r . ' ' . $str . ($r > 1 ? 's' : '') . ' ago';
}
}
}
In this function you can get "(1) second/minute/hour/day/month/year ago"

Get normal user readable date/time with php

I know this question has been asked 2-3 times before, and I am using a function which I found in one of the answers(check it here) from those questions, but it doesnt seem to be working fine for me, i asked there in comments but didnt get any reply, so I am opening a new question here. following is the code to get plain text date/time from a datetime(mysql type).
function getElapsedTime($time_stamp)
{
$ts = convert_datetime($time_stamp);
$time_stamp = $ts;
$time_difference = strtotime('now') - $time_stamp;
if ($time_difference >= 60 * 60 * 24 * 365.242199)
{
return get_time_ago_string($time_stamp, 60 * 60 * 24 * 365.242199, 'year');
}
elseif ($time_difference >= 60 * 60 * 24 * 30.4368499)
{
return get_time_ago_string($time_stamp, 60 * 60 * 24 * 30.4368499, 'month');
}
elseif ($time_difference >= 60 * 60 * 24 * 7)
{
return get_time_ago_string($time_stamp, 60 * 60 * 24 * 7, 'week');
}
elseif ($time_difference >= 60 * 60 * 24)
{
return get_time_ago_string($time_stamp, 60 * 60 * 24, 'day');
}
elseif ($time_difference >= 60 * 60)
{
return get_time_ago_string($time_stamp, 60 * 60, 'hour');
}
elseif($time_difference <= 60)
{
return get_time_ago_string($time_stamp, 60, 'minute');
}
}
function get_time_ago_string($time_stamp, $divisor, $time_unit)
{
$time_difference = strtotime("now") - $time_stamp;
$time_units = floor($time_difference / $divisor);
settype($time_units, 'string');
if ($time_units === '0')
{
return 'less than 1 ' . $time_unit . ' ago';
}
elseif ($time_units === '1')
{
return '1 ' . $time_unit . ' ago';
}
else
{
return $time_units . ' ' . $time_unit . 's ago';
}
}
function convert_datetime($str) {
list($date, $time) = explode(' ', $str);
list($year, $month, $day) = explode('-', $date);
list($hour, $minute, $second) = explode(':', $time);
$timestamp = mktime($hour, $minute, $second, $month, $day, $year);
return $timestamp;
}
I have added one more function convert_datetime() which turns mysql datetime date into timestamp, as I thought the function getElapsedTime() is expecting timestamp, because when I was passing normal datetime date(mysql format), it wasn't working. So now, I am passing mysql datetime to getElapsedTime() and converting it into timestamp using convert_datetime() function and using it to get string.
But when the date is expected to return for "minute" or "second", its returning in negative value. eg its returning "-182 minutes ago" for "2013-05-23 15:59:58"..
Anybody knows how to get it done?
This is much simpler using PHP's DateTime classes:-
function time_ago($time_stamp)
{
$time = new DateTime($time_stamp);
$now = new DateTime();
$diff = $now->diff($time);
return $diff->format("%h hours, %i minutes ago");
}
$diff is an instance of DateInterval.
If you wish you can specify the format you are receiving in $time_stamp by using:-
$time = DateTime::createFromFormat('Your format here');
Obviously you can adjust the output format to suit.
// try this function
function time_ago($ptime) {
$ptime = strtotime($ptime);
if ($ptime) {
$etime = time() - $ptime;
if ($etime < 1)
return 'few seconds';
$a = array(
12 * 30 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($a as $secs => $str) {
$d = $etime / $secs;
if ($d >= 1) {
$r = round($d);
return $r . ' ' . $str . ($r > 1 ? 's' : '') . '';
}
}
}
return '0';
}
// usage
echo time_ago('2013-05-23 15:59:58');
echo time_ago(date('Y:m:d H:i:s'));
// Output
43 minutes
few seconds

converting php mysql time to seconds ago

im having a problem converting time. for some reason it seems to be defaulting back to 1970 which i believe is unix default time. im using this code, when i run the program i get 42years instead of 2 years. what am i missing. please help
here is the code
<?php
function convertime($ptime) {
$etime = time() - $ptime;
if($etime < 60) {
return 'less than minute ag';
}
$a = array(12 * 30 * 24 * 60 * 60 => 'year', 30 * 24 * 60 * 60 => 'month', 24 * 60 * 60 => 'day', 60 * 60 => 'hour', 60 => 'minute' // 1 => 'second'
);
foreach($a as $secs => $str) {
$d = $etime / $secs;
if($d >= 1) {
$r = round($d);
return $r . ' ' . $str . ($r > 1 ? 's' : '');
}
}
}
?>
<?php
$ctime = 2009-02-23 10:09:00 //time from mysql
echo convertime($ctime);
?>
Wrap strtotime() around your timestamp:
$ctime = strtotime('2009-02-23 10:09:00'); //time from mysql
http://codepad.org/HWQrLwBy
You need to compare a timestamp to a timestamp.
<?php
function convertime($ptime) {
$etime = time() - $ptime;
if($etime < 60) {
return 'less than minute ag';
}
$a = array(12 * 30 * 24 * 60 * 60 => 'year', 30 * 24 * 60 * 60 => 'month', 24 * 60 * 60 => 'day', 60 * 60 => 'hour', 60 => 'minute' // 1 => 'second'
);
foreach($a as $secs => $str) {
$d = $etime / $secs;
if($d >= 1) {
$r = round($d);
return $r . ' ' . $str . ($r > 1 ? 's' : '');
}
}
}
?>
<?php
$ctime = strtotime('2009-02-23 10:09:00'); //time from mysql
echo convertime($ctime);
?>
try it

php date formatting for time difference

I just want to output as a result of a script to be executed through CLI the time the execution of the script took.
for doing that, I set a var at the start of the script
$start_time = time();
and then at the end
date('H:i:s',time() - $start_time);
the problem is that even when the ellapsed time might be in the range of seconds or minutes, it always print that at least an hour has passed:
>>> echo date('H:i:s',1);
01:00:01
>>> echo date('H:i:s', 10);
01:00:10
>>> echo date('H:i:s',3599);
01:59:59
>>> echo date('H:i:s',3600);
02:00:00
shouldn't it display 00:XX:YY, when less than an hour has passed?
is there something I'm missing, is there a bug?
thanks for your help!
Don't use date(). When you have time() - $start_time the result is in seconds. Multiply this up if you want it in mintues etc. or use the following function to convert the seconds to Hours, Minutes and Seconds.
<?php /**
*
* #convert seconds to hours minutes and seconds
*
* #param int $seconds The number of seconds
*
* #return string
*
*/
function secondsToWords($seconds) {
/*** return value ***/
$ret = "";
/*** get the hours ***/
$hours = intval(intval($seconds) / 3600);
if($hours > 0)
{
$ret .= "$hours hours ";
}
/*** get the minutes ***/
$minutes = bcmod((intval($seconds) / 60),60);
if($hours > 0 || $minutes > 0)
{
$ret .= "$minutes minutes ";
}
/*** get the seconds ***/
$seconds = bcmod(intval($seconds),60);
$ret .= "$seconds seconds";
return $ret;
} ?>
Example usage:
<?php
/*** time since EPOCH ***/
echo secondsToWords(time());
?>
You could try this function:
<?
$time = strtotime('2010-04-28 17:25:43');
echo 'event happened '.humanTiming($time).' ago';
function humanTiming ($time)
{
$time = time() - $time; // to get the time since that moment
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
return $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
}
}
?>
From here:
PHP How to find the time elapsed since a date time?
This will give you a better means of getting the difference. Simply replace strtotime('2010-04-28 17:25:43'); with whatever your start date/time is (as a timestamp). One of the benefits is the function can be repurposed elsewhere.
Try this:
echo "Time left:". date('H:i:s', (strtotime('2000-01-01 00:00:00') + (time()-$start_time) ));
Use gmdate() instead of date() to display the correct time difference and compensate for the server's time zone
This function gives a "fully" formatted human readable time string..
function humantime ($oldtime, $newtime = null, $returnarray = false) {
if(!$newtime) $newtime = time();
$time = $newtime - $oldtime; // to get the time since that moment
$tokens = array (
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
$htarray = array();
foreach ($tokens as $unit => $text) {
if ($time < $unit) continue;
$numberOfUnits = floor($time / $unit);
$htarray[$text] = $numberOfUnits.' '.$text.(($numberOfUnits>1)?'s':'');
$time = $time - ( $unit * $numberOfUnits );
}
if($returnarray) return $htarray;
return implode(' ', $htarray);
}

Categories