"Time ago" from MySQL timestamp - php

I'm trying to make a table of results including the timestamp for each entry from the database. However, I need the time to be displayed as "X seconds/minutes/hours ago".
I've tried the jQuery timeago plugin with zero success and am now wondering how to do this for each entry.
$result = mysql_query("SELECT * from realmfeed order by ID asc");
echo "<table class='display'>\n";
while($row = mysql_fetch_array($result))
{
echo "<tr><td><b>".$row['ID']."</b></td>\n";
echo "<td>".$row['eventType']."</td>\n";
echo "<td>".$row['server']."</td>\n";
echo "<td>".$row['realm']."</td>\n";
echo "<td>".$row['name']."</td>\n";
echo "<td>".$row['time']."</td>\n</tr>\n\n";
}
echo "</table>\n";
How is it possible to create a "time ago" function for each result?

$time = strtotime($row['time']);
$dbDate = new DateTime($time);
$currDate = new DateTime();
$interval = $currDate->diff($dbDate);
echo $interval->d." days ".$interval->h." hours";
please refer to DateInterval for available functions and fields

The problem with using PHP to do the time difference calculations is you're assuming the MySQL and PHP servers are in the same time zones. Better to do the difference calculation in the SELECT:
SELECT TIMEDIFF(NOW(), `time`) AS ago FROM realmfeed ORDER BY ID ASC
This will return hh:mm:ss formatted time difference.
Or if you'd prefer just the number of seconds:
SELECT TIME_TO_SEC(TIMEDIFF(NOW(), `time`)) AS secondsAgo FROM realmfeed ORDER BY ID ASC

I would get the time stamp from MYSQL then do the maths in php eg.
$result = mysql_query("SELECT ..., UNIX_TIMESTAMP(time) as time FROM realfeed ORDER BY ID ASC");
$row = mysql_fetch_array($result);
$then = $row['time'];
$now = time();
$diff = $now - $then; //Now you have the difference in seconds
There is a nice function here you could use the difference on although I have not checked it myself.....
http://itwigle.com/twig/PHP_Time_Ago_Function

try this this may help
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="jquery.timeago.js"></script>
</head>
<body>
<?php
$result = mysql_query("SELECT * from realmfeed order by ID asc");
echo "<table class='display'>\n";
while($row = mysql_fetch_array($result))
{
echo "<tr><td><b>".$row['ID']."</b></td>\n";
echo "<td>".$row['eventType']."</td>\n";
echo "<td>".$row['server']."</td>\n";
echo "<td>".$row['realm']."</td>\n";
echo "<td>".$row['name']."</td>\n";
echo "<td><abbr class=\"timeago\" title=\"".date("j F Y h:i:s A",$row['time'])."\"></abbr></td>\n</tr>\n\n";
}
echo "</table>\n";
?>
<script>
jQuery(document).ready(function($){
$("abbr.timeago").timeago()
});
</script>
</body>
</html>

Related

Recommendation script not working when trying to combine both components

Context
I am building a simple recommendation script that serves to provide a user with the next upcoming date for a particular day of the week that he/she has booked the most.
(i.e. JohnDoe's most popular day to book is a Thursday, and the date of the next Thursday to come up is 2019/03/07)
This is what I am dealing with :
<?php
$date = new DateTime();
$date->modify('next thursday');
echo $date->format('Y-m-d');
?>
<?php require "snippets/get_booking_recommended_day.php" ?>
The first PHP code returns the next upcoming date for whatever day is asked. It works as it should. The PHP require references code from another folder that returns the users most popular day, in String format. (eg Monday, Tuesday). It also works.
My issue comes when trying to get the first bit of code to understand what is being returned from the 2nd bit of code.
I've attempted the following...
<?php
$date = new DateTime();
$date->modify('next' require "snippets/get_booking_recommended_day.php");
echo $date->format('Y-m-d');
?>
I've tried every variation possible. Nothing seems to work.
I'm quite new to PHP, and im 90% sure my coding practice is terrible but I am trying my best to grasp it - but so far this simple issue is beyond me.
Please help.
APPENDICES
Filename: snippets/get_booking_recommended_day.php
(Return the most booked day of the last 3 months by the user currently in session)
<?php
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
// Asks the qry: Of the last 90 days, what is the most booked day of the week for the current member in session?
// Min date is CURRENT_DATE() -100 instead of CURRENT_DATE() -30, because the MySQL function CURRENT_DATE() prints the date in an int format (YYYYMMDD) with no date formatting. Thus, to get the date a month ago, we must subtract this int by 100 so as to remove 1 from the 6th number in the series of numbers. Which is the 2nd M number.
$sql = "SELECT DATE_FORMAT(tbl_booking.booking_date, '%W'), COUNT(DATE_FORMAT(tbl_booking.booking_date, '%W')) AS mostpopularday
FROM tbl_booking
WHERE tbl_booking.member_ID=$_SESSION[member_ID]
AND tbl_booking.booking_date <= CURRENT_DATE()
AND tbl_booking.booking_date >= CURRENT_DATE() -300
GROUP BY DATE_FORMAT(tbl_booking.booking_date, '%W')
ORDER BY mostpopularday DESC
LIMIT 1";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["DATE_FORMAT(tbl_booking.booking_date, '%W')"];
}
} else {
// Return Nothing.
}
?>
Filename : pagebooking.php
(This is the datepicker that is located inside my pagebooking.php, its purpose is to choose the day of a booking. My hope is to populate this field with the recommended date that will be generated from the 2 PHP scripts above.).
<input name="new_booking_date" width="276" placeholder="Date" class="form-control input-md" type="date" max="<?php echo date("Y-m-d", strtotime("+30 day")); ?>" min="<?php echo date("Y-m-d", strtotime("+1 day")); ?>" required="" />
Issue resolved.
<?php
// If there are any values in the table, display them one at a time.
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
// Asks the qry: Of the last 90 days, what is the most booked day of the week for the current member in session?
// Min date is CURRENT_DATE() -100 instead of CURRENT_DATE() -30, because the MySQL function CURRENT_DATE() prints the date in an int format (YYYYMMDD) with no date formatting. Thus, to get the date a month ago, we must subtract this int by 100 so as to remove 1 from the 6th number in the series of numbers. Which is the 2nd M number.
$sql = "SELECT DATE_FORMAT(tbl_booking.booking_date, '%W'), COUNT(DATE_FORMAT(tbl_booking.booking_date, '%W')) AS mostpopularday
FROM tbl_booking
WHERE tbl_booking.member_ID=$_SESSION[member_ID]
AND tbl_booking.booking_date <= CURRENT_DATE()
AND tbl_booking.booking_date >= CURRENT_DATE() -300
GROUP BY DATE_FORMAT(tbl_booking.booking_date, '%W')
ORDER BY mostpopularday DESC
LIMIT 1";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$recommended_day = $row["DATE_FORMAT(tbl_booking.booking_date, '%W')"];
$date = new DateTime();
$date->modify('next '.$recommended_day);
echo $date->format('Y-m-d');
}
} else {
}
?>

round down to nearest 5 mintues php mysqli

I"m trying to get this time code to round down to the nearest time
example if the time listed is 10:28, then i want it to show 10:25
What I have is (the time modify is required)
<?php
include('../../database/2ndconnection.php');
$sql="SELECT * FROM raid ORDER BY TimeRecord DESC LIMIT 1";
$result=mysqli_query($dbcon,$sql);
while($rows=mysqli_fetch_array($result)){
$dateStr = $rows['TimeRecord'];
$pst = new \DateTime($dateStr);
$pst->modify("-3 hours");
$est = new \DateTime($dateStr);
} ?>
PST: <?php echo $pst->format('H:i'); ?>
<br>EST: <?php echo $est->format('H:i'); ?>
thanks in advance for your help
Insert this:
<?php
$currentMinutes = $time->format('i');
$minutesToSubtract = $currentMinutes % 5;
$time = $time->sub(new DateInterval('M' . $minutesToSubtract));
?>
$currentMinutes will hold the current number of minutes, using %, you can compute the minutes that need to be subtracted, and afterwards you subtract them through the sub function
It could be integrated into your code as following:
<?php
include('../../database/2ndconnection.php');
$sql="SELECT * FROM raid ORDER BY TimeRecord DESC LIMIT 1";
$result=mysqli_query($dbcon,$sql);
while($rows=mysqli_fetch_array($result)){
$dateStr = $rows['TimeRecord'];
$pst = new \DateTime($dateStr);
$pst->modify("-3 hours");
$est = new \DateTime($dateStr);
}
$currentMinutes = $pst->format('i');
$minutesToSubtract = $currentMinutes % 5;
$pst = $pst->sub(new DateInterval('M' . $minutesToSubtract));
?>
PST: <?php echo $pst->format('H:i'); ?>
<br>EST: <?php echo $est->format('H:i'); ?>

PHP check if event has started

Im using the following mysql script to display a list of active / upcoming fixtures.
Select * FROM schedule
WHERE schedule.gameDate > CURDATE() OR
( schedule.gameDate = CURDATE() and schedule.gameTime > CURTIME() )
GROUP BY schedule.tournament
ORDER By schedule.gameDate
The above script works perfectly.
However, as an additional check to prevent a user from accessing a fixture which has expired im doing the following.
$curTime = date('H:i:s');
$curDate = date('Y-m-d');
$sql = "SELECT * FROM schedule
WHERE tournament = :tour AND weekNum = :round";
$stmnt = $db->prepare($sql);
$stmnt->bindValue(':tour',$tournament);
$stmnt->bindValue(':round', $round);
$stmnt->execute();
$results = $stmnt->fetchAll();
foreach($results as $result){
echo $eventDate = $result['gameDate'];
echo $startTime = $result['gameTime'];
if($curDate > $eventDate){
echo '<h1> CURRENT ROUND ALLREADY STARTED</h1>';
die();
}//if
else if($eventDate==$curDate && $curTime>$startTime){
echo '<h1> CURRENT ROUND ALLREADY STARTED</h1>';
die();
}//else if
}//foreach
My Problem.
The loop never passes the first IF statment which always results to true...
DB Table
When I echo the variables I get the following:
$curTime = 09:30:00
$curDate = 2017-19-03
$eventDate = 2017-03-21
$startTime = 13:00:00
I realize it is not the prettiest code but according to my little experience and logic it should pass both if statments...
Any advise appreciated
Use strtotime() in compare two date in php
Replace if($curDate > $eventDate) with if(strtotime($curDate) > strtotime($eventDate)) and other comparison also
You can convert them to DateTime objects or timestamps to compare. String comparison will only check whether they are equal or not.
So:
$now = new DateTime();
$event = new DateTime($eventDate . ' ' . $startTime);
Then you can check whether dates are equal or later the same way you're already doing. See Example #2 on the Date Diff page of the php website. E.g. $now > $event, etc.
It should be elseif.not else if. There should not be a space between else and if.

Subtract fetched datetime from current date time

I need to calculate the time difference between the localDatetime and a Datetime fetched from a specific row in my database-table(csv) called ReportedDateAndTime. I searched a lots of solutions but it doesn't working for me. Displaying localtime & the fetched time from Database are working. But the time difference doesn't. Here is my code so far. Please help. Thanks in advance!
<?php
include_once('connection.php');
$sql="SELECT * FROM csv";
$records=mysqli_query($conn, $sql);
$date = new DateTime(null, new DateTimeZone('Asia/Colombo'));
while ($csv=mysqli_fetch_assoc($records))
{
$exp = $csv['ReportedDateAndTime'];
}
$diff = $date->diff($exp);
echo $diff->format('%H')
?>
From the mysql doc
SELECT CONVERT_TZ('2004-01-01 12:00:00','GMT','MET');
'2004-01-01 13:00:00'
SELECT CONVERT_TZ('2004-01-01 12:00:00','+00:00','+10:00');
'2004-01-01 22:00:00'
https://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html
Thanks all. Fortunately I found an answer. :)
<?php
include 'connection.php';
date_default_timezone_set('Asia/Colombo');
$the_time = date('H:i');
echo $the_time." </br>";
$sql="SELECT ReportedDateAndTime FROM csv";
$result=$conn->query($sql);
while ($row = $result->fetch_assoc())
{
$new_time=$row['ReportedDateAndTime'];
echo "<br/>";
echo $new_time." ReportedDateAndTime</br>";
$datetime1 = new DateTime($the_time);
$datetime2 = new DateTime($new_time);
$interval = $datetime1->diff($datetime2);
$hours=$interval->format('%h');
$minutes= $interval->format('%i');
echo "<br/>";
echo $hours." Hours ".$minutes." Minutes</br></br>";
}
?>

How to search birthday from December to January in MySQL?

This is for my OJT project. I need to search birthday from MySQL database in DATE type. I already got the query from January to December. The December to January is the problem.
This is what i've done code so far:
<?php
require 'connect.php';
?>
<?php
if(isset($_POST['birthday_from']) && isset($_POST['birthday_to'])){
$start_date=$_POST['birthday_from'];
$end_date=$_POST['birthday_to'];
//$s = strtolower($end_date);
$start_year = date('m-d', strtotime($start_date));
$end_year = date('m-d', strtotime($end_date));
$search_year = date('Y', strtotime($start_date));
$search_year2 = date('Y', strtotime($end_date));
$sql=" select * from members where (DATE_FORMAT(`birthday`, '%m-%d') BETWEEN '{$start_year}' AND '{$end_year}') order by DATE_FORMAT(`birthday`, '%m-%d') asc ";
$result = mysql_query($sql);
$num_row = mysql_num_rows($result);
if($num_row >= 1){
echo '<div class="alert alert-info" style="margin:auto;width:900px;"><b><center>BIRTHDAY RESULT</center></b></div>';
while($rows = mysql_fetch_array($result)){
$date = date('Y-m-d')-$rows['birthday'];
echo '<b><span style="margin-left:20px;">Name:</span></b> '.strtoupper($rows['firstname'].' '.$rows['middlename'].' '.$rows['lastname'].' '.$rows['suffix']).'<br/>';
echo '<b><span>Birthday:</span></b> '.$rows['birthday'].'<br/>';
echo '<b><span style="margin-left:30px;">Age: </span></b>'.$date.'<br/><br />';
}
}
}
?>
You do not check the case when start date > end date. It is happens.
You named var $start_year = date('m-d', strtotime($start_date)), but there is no any Year in value. It is bad practice.
You do not use vars search_year, search_year2 after defining and assigning.
I do not understand what You want, can You give the example with several rows in table and result what You want to get but You cannot?
Looks like you're using the wrong variables for your BETWEEN statement.
BETWEEN '{$start_year}' AND '{$end_year}'
should be:
BETWEEN '{$seach_year}' AND '{$search_year2}'

Categories