Here is a PHP function I have designed, which is supposed to determine the amount of time passed in secs,mins,hours,days,weeks,months, and years - depending upon which bracket it is beneath. However Ive noticed that the values being returned seem to increase faster than actual time (within 30 mins, it outputs "1 weeks ago"). Im wondering if $time is actually in millis? That said, for the first 2 mins it outputs relatively accurate results.
Note: Running on 1and1 host.
Here's the function:
function get_relative_date($conn,$date,$post_id){
#get current timestamp
$q = "SELECT NOW() - INTERVAL 1 HOUR - `timestamp` FROM `posts` WHERE id=".$post_id.";";
# - INTERVAL 1 HOUR added due to server running 1 hour ahead.
$result = mysqli_query($conn,$q);
if ($result != null && $result != false){
$row = mysqli_fetch_array($result,MYSQLI_BOTH);
$time = $row[0]; #time passed since post
$min = 60;
$hour = $min*60;
$day = $hour*24;
$week = $day*7;
$month = $week*4;
$year = $month*12;
if ($time < $min){
return $time." secs ago";
}
if ($time < $hour){
return round(($time / $min))." mins ago";
}
if ($time < $day){
return round(($time / $hour))." hours ago";
}
if ($time < $week){
return round(($time / $day))." days ago";
}
if ($time < $month){
return round(($time / $week))." weeks ago";
}
if ($time < $year){
return round(($time / $month))." months ago";
}
if ($time >= $year){
return round(($time / $year))." years ago.";
}
return false;
}
}
Cheers.
I tried your query out and instead of 2 minutes and 40 seconds (in seconds) I was receiving 240 and instead of 1 hour 3 minutes and 40 seconds (in seconds) I got 10340.
You need this:
SELECT TIME_TO_SEC(TIMEDIFF(NOW(),`timestamp`)) FROM `posts` ...
This will select the time difference in seconds and hopefully give you the desired result.
Related
PHP Function to convert time() seconds to time format Hour:Minutes
function secondsToTime($seconds) {
$dtF = new \DateTime('#0');
$dtT = new \DateTime("#$seconds");
// return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds');
return $dtF->diff($dtT)->format('%h:%i');
}
echo secondsToTime(time());
I need a function for something like:
If time now is 23:41 (hour:minute) to show 23:40
If time now is 23:46 (hour:minute) to show 23:45
If time now is 23:47 (hour:minute) to show 23:45
If time now is 23:49 (hour:minute) to show 23:45
If time now is 23:52 (hour:minute) to show 23:50
But the output to be show by time() format seconds so this way i can check via mysql how many rows updated from time() format show 23:45 if time now is 23:49 so in past 4 minutes ...
You need to round the minutes and then reformat your output date.
There's some gotchas hidden in here. As you can end up with 60 minutes (should be 00) and 24 hours (also should be 00). So special checks are put in place to catch that.
Also, you way of getting the current time is very convoluted. Getting "now" gets the same value which is what DateTime() gets by default.
function secondsToTime() {
$now = new \DateTime();
$cminutes = $now->format('i');
$hour = $now->format('H');
$nminutes = (round($cminutes)% 5 === 0) ? round($cminutes) : round(($cminutes + 5 / 2) / 5 ) * 5;
if ($nminutes > $cminutes) {
$nminutes -= 5;
}
if ($nminutes === 60) {
$nminutes = 0;
$hour++;
}
if ($hour === 24) {
$hour = 0;
}
return sprintf('%02d:%02d', $hour, $nminutes);
}
echo secondsToTime();
Demo
This question already has answers here:
Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...
(32 answers)
How to convert hh:mm:ss to minutes
(7 answers)
Closed 4 years ago.
$time_frame = floor(abs((strtotime($notification['note_date'])-strtotime(date("Y-m-d H:i:s")))/60/60));
if($time_frame>24){
$time_frame = floor($time_frame/24);
if($time_frame>1){
$time_frame = $time_frame." days ago";
} else{
$time_frame = $time_frame." day ago";
}
} else if($time_frame>1) {
$time_frame = $time_frame." hours ago";
} else if($time_frame==1) {
$time_frame = $time_frame." hour ago";
} else{
$time_frame = "1 hour ago"; //I want to break this hour in to minutes
}
How do i break that hour in to display in to minutes, last else statement.
I recommend dealing with seconds/timestamps or date-time objects instead - this would be a better and more dynamic approach in my opinion. Perhaps have a look at this question instead Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...
That said, if you want to do it with your current approach, you can multiply your variable by 60 (as there is 60 minutes in an hour), such as
$time_frame = 60*$timeframe;
Examples,
If $timeframe is 1, then you have exactly one hour. 60min * 1 = 60 minutes.
If $timeframe is 0.5, that would be half an hour. 60min * 0.5 = 30 minutes.
If $timeframe is 0.25, means that 15 minutes have passed, and 60min * 0.25 = 15 minutes.
You might want to round that number to your liking, so that you will not get output such as 1.43 minutes left. Also note that floating point numbers may not be exactly accurate, hence my recommendation of using datetime objects or timestamps instead.
If you use the DateTime class, you can use the diff() method so you don't have to mess with all the calculating. diff() returns a DateInterval which has public properties you can use to determine the appropriate message.
$interval = date_create($notification['note_date'])->diff(new DateTime);
if ($interval->days > 1) {
$time_frame = "{$interval->days} days";
} elseif ($interval->days == 1) {
$time_frame = "1 day";
} elseif ($interval->h > 1) {
$time_frame = "{$interval->h} hours";
} elseif ($interval->h == 1) {
$time_frame = "1 hour";
} elseif ($interval->i > 1) {
$time_frame = "{$interval->i} minutes";
} elseif ($interval->i == 1) {
$time_frame = "1 minute";
} else {
$time_frame = "Less than 1 minute";
}
echo "{$time_frame} ago";
You can actually USE that string! :-D
$x = new DateTime('1 hour ago'); // done at 17:17
echo $x->format('Y-m-d H:i:s'); // outputs 2018-10-23 16:17:12
https://3v4l.org/jWTC8
Convert 2010-04-16 16:30:00 to "Tomorrow Afternoon" or convert another date to "this afternoon", "next year", "next week wednesday". You get the picture.
Anyone know of a PHP or Javascript library that can do this?
I think you can come a long way with what is said here: Calculate relative time in C#
The logic is there, and it's not too hard to do the javascript equivalent if a solution in a different language suits you.
There might be more elegant solutions out there (look for Natural language formatting), but personally I couldn't find any.
I would suggest calculating the distance from now to the date you're formatting, and using thresholds.
Pseudo solution:
diff = now - date
if (diff < one_day)
format for today
if (diff < two_days)
format for tomorrow
if (diff < one_week)
format using days from now
.
.
.
The comparison will work for both past and future dates, as long as you use compare with the abs value of diff. Display timeunit ago or timeunit from now by checking if diff is positive or negative.
For the morning, afternoon, evening etc. you only need to check for the time of day in the date, and regarding the formatting type you hit, either display the time as numbers (far away), or natural language (recent or near date).
function gett($sam){
$times = time() - $sam;
if ($times == 60){
$times = "a minute ago";
}
if (($times != 1) && ($times < 60) && ($times != 0)){
$times = "$times seconds ago";
}
if ($times == 0){
$times = "less than a second ago";
}
if ($times == 1){
$times = "a second ago";
}
if ($times > 60 && $times < 3600){
$times = ceil($times/60)." minutes ago";
}
if($times == 3600){
$times = "an hour ago";
}
if($times > 3600 && $times < 86400){
$times = ceil($times/3600)." hours ago";
}
if($times == 86400){
$times = "a day ago";
}
if($times > 86400){
$times = ceil($times/86400)." days ago";
}
return $times; }
Usage:
$updated = gett($timestamp);
where $timestamp is pretty self-explanatory..
From this link -> How do I calculate relative time in C#?
function posted(t) {
var now = new Date();
var diff = parseInt((now.getTime() - Date.parse(t)) / 1000);
if (diff < 60) { return 'less than a minute ago'; }
else if (diff < 120) { return 'about a minute ago'; }
else if (diff < (2700)) { return (parseInt(diff / 60)).toString() + ' minutes ago'; }
else if (diff < (5400)) { return 'about an hour ago'; }
else if (diff < (86400)) { return 'about ' + (parseInt(diff / 3600)).toString() + ' hours ago'; }
else if (diff < (172800)) { return '1 day ago'; }
else {return (parseInt(diff / 86400)).toString() + ' days ago'; }
}
Okay, so, I have a list table with 2 columns: codes and dates.
I want to display the LATEST 25 AND tell the user how long ago they were submitted.
So, for example:
ABCDEF (1 Second Ago)
CCDEE (12 Seconds Ago)
329492 (45 Minutes Ago)
I've gotten this far:
$result = mysql_query("SELECT `code` FROM `fc` ORDER by datetime LIMIT 25") or die(mysql_error());
but, it doesn't do what I want. It does the reverse. It shows what was inputted FIRST, not LAST.
My output looks like this:
$output .= "<li>" . htmlspecialchars($fetch_array["code"]) . "</li>";
I have NO Idea how to add the (time since) part.
Help?
Thanks :)
Consider ORDER BY datetime DESC to sort in the other direction.
Consider adding datetime to the SELECT list, so you can access the posting date in PHP. You can then use PHP date/time functions to calculte the difference between the current date, and the date posted, to work out how long ago the posting was posted.
Added: a bit of code to calculate the time since the posting in a friendly format.
$seconds = time() - strtotime($fetch_array["datetime"]);
if($seconds < 60)
$interval = "$seconds seconds";
else
if($seconds < 3600)
$interval = floor($seconds / 60) . " minutes";
else
if($seconds < 86400)
$interval = floor($seconds / 3600) . " hours";
else
$interval = floor($seconds / 86400) . " days";
// You can keep on going
At the end $interval contains a textual representation of the interval
Try using
order by datetime desc
Then in PHP grab the current time, subtract the time returned from the query, and then take a look at this SO question about relative time to display your time in the proper units.
If I understand right the question the problem is that you don't specify the order of sort.
If you want to obtain the latest posts you have to specify the descendant order.
$result = mysql_query("SELECT code FROM fc ORDER by datetime DESC LIMIT 25") or die(mysql_error());
To fix the ordering:
"SELECT `code`, `datetime` FROM `fc` ORDER by datetime DESC LIMIT 25"
To get time diff, something like this should work. Note that you should refactor this into better methods, remove the "magic number" etc. (It can also be extended to be more sophisticated):
function getTimeAgo ($dateTime) {
$timestamp = new DateTime($dateTime);
$currentTimestamp = new DateTime();
$diff = $currentTimestamp->getTimestamp() - $timestamp->getTimestamp();
if($diff < 0) {
throw new Exception (__METHOD__ . ':parameter $dateTime can not be
in the future!');
}
if($diff < 60) {
return "$diff seconds ago";
}
if($diff < 3600) {
return $diff/60 . " minutes ago";
}
if($diff < 86400) {
return $diff/3600 . " hours ago";
}
}
Changing datetime order:
Try DESC or ASC at the end of your ORDER BY. This should do the trick:
SELECT code
FROM fc
ORDER BY datetime DESC
LIMIT 25
Time since:
Write or find a PHP function that converts MySQL datetime format to 'real English'. Here's a quick basic example:
<?php
// your code goes here
$timeStr = "2009-08-01 15:43:34";
$time = Sec2Time( time() - strtotime($timeStr) );
print_r($time);
// this converts mysql datetime into english
// borrowed from http://ckorp.net/sec2time.php
function Sec2Time($time){
if(is_numeric($time)){
$value = array(
"years" => 0, "days" => 0, "hours" => 0,
"minutes" => 0, "seconds" => 0,
);
if($time >= 31556926){
$value["years"] = floor($time/31556926);
$time = ($time%31556926);
}
if($time >= 86400){
$value["days"] = floor($time/86400);
$time = ($time%86400);
}
if($time >= 3600){
$value["hours"] = floor($time/3600);
$time = ($time%3600);
}
if($time >= 60){
$value["minutes"] = floor($time/60);
$time = ($time%60);
}
$value["seconds"] = floor($time);
return (array) $value;
}else{
return (bool) FALSE;
}
}
?>
And the output is:
Array ( [years] => 0 [days] => 4 [hours] => 5 [minutes] => 29 [seconds] => 38 )
Hope that helps
I have a Date object ( from Pear) and want to subtract another Date object to get the time difference in seconds.
I have tried a few things but the first just gave me the difference in days, and the second would allow me to convert one fixed time to unix timestamp but not the Date object.
$now = new Date();
$tzone = new Date_TimeZone($timezone);
$now->convertTZ($tzone);
$start = strtotime($now);
$eob = strtotime("2009/07/02 17:00"); // Always today at 17:00
$timediff = $eob - $start;
** Note ** It will always be less than 24 hours difference.
Still gave somewhat wrong values but considering I have an old version of PEAR Date around, maybe it works for you or gives you an hint on how to fix :)
<pre>
<?php
require "Date.php";
$now = new Date();
$target = new Date("2009-07-02 15:00:00");
//Bring target to current timezone to compare. (From Hawaii to GMT)
$target->setTZByID("US/Hawaii");
$target->convertTZByID("America/Sao_Paulo");
$diff = new Date_Span($target,$now);
echo "Now (localtime): {$now->format("%Y-%m-%d %H:%M:%S")} \n\n";
echo "Target (localtime): {$target->format("%Y-%m-%d %H:%M:%S")} \n\n";
echo $diff->format("Diff: %g seconds => %C");
?>
</pre>
Are you sure that the conversion of Pear Date object -> string -> timestamp will work reliably? That is what is being done here:
$start = strtotime($now);
As an alternative you could get the timestamp like this according to the documentation
$start = $now->getTime();
To do it without pear, to find the seconds 'till 17:00 you can do:
$current_time = mktime ();
$target_time = strtotime (date ('Y-m-d'. ' 17:00:00'));
$timediff = $target_time - $current_time;
Not tested it, but it should do what you need.
I don't think you should be passing the entire Date object to strtotime. Use one of these instead;
$start = strtotime($now->getDate());
or
$start = $now->getTime();
Maybe some folks wanna have the time difference the facebook way. It tells you "one minute ago", or "2 days ago", etc... Here is my code:
function getTimeDifferenceToNowString($timeToCompare) {
// get current time
$currentTime = new Date();
$currentTimeInSeconds = strtotime($currentTime);
$timeToCompareInSeconds = strtotime($timeToCompare);
// get delta between $time and $currentTime
$delta = $currentTimeInSeconds - $timeToCompareInSeconds;
// if delta is more than 7 days print the date
if ($delta > 60 * 60 * 24 *7 ) {
return $timeToCompare;
}
// if delta is more than 24 hours print in days
else if ($delta > 60 * 60 *24) {
$days = $delta / (60*60 *24);
return $days . " days ago";
}
// if delta is more than 60 minutes, print in hours
else if ($delta > 60 * 60){
$hours = $delta / (60*60);
return $hours . " hours ago";
}
// if delta is more than 60 seconds print in minutes
else if ($delta > 60) {
$minutes = $delta / 60;
return $minutes . " minutes ago";
}
// actually for now: if it is less or equal to 60 seconds, just say it is a minute
return "one minute ago";
}