round down to nearest 5 mintues php mysqli - php

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'); ?>

Related

PHP using TIME from database to calculate hours

<?php
require 'dbfunction.php';
$con = getDbConnect();
if (!mysqli_connect_errno($con)) {
$queryStr = "SELECT * " .
"FROM crewlist WHERE crew_name = 'Peter'";
}
$result = mysqli_query($con, $queryStr);
while ($row = mysqli_fetch_array($result)) {
$a = new DateTime($row["start_hour"]);
$b = new DateTime($row["end_hour"]);
$shift1 = $a->diff($b);
$c = new DateTime($row["start_hour2"]);
$d = new DateTime($row["end_hour2"]);
$shift2 = $c->diff($d);
if ($shift1 > 60*60*14) {
echo 'no';
}
?>
I am trying to deduce the difference between my shift timings, with the condition of (for e.g. shift 1 not exceeding 14 hours). Thanks in advance. The fields of my form is using time as the type.
Convert your start date and end date into timestamp and then take difference of both.
$diff = abs($start-$end)
if($diff > 60 * 60 *14 ){
// Your desired statement
}
if that difference exceeds to 60*60*14 then it will exceed to 14 hour.

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>";
}
?>

MYSQL's Timestampdiff not working with PHP's if/else bigger than >

The following Mysql SELECT-part of Timestampdiff
$result_all = mysql_query("SELECT *, TIMESTAMPDIFF(MINUTE,aktualisiert,NOW()) AS quote_diff FROM sms WHERE gesendet ='1' AND DATE_FORMAT( aktualisiert, '%Y' ) = '2015' AND trash ='0' ORDER BY aktualisiert DESC");
seems not to work with the if else PHP Code
<?php
$qd = $row['quote_diff'];
$qdint = intval($qd);
$zahl = intval(100);
echo $qdint;
if ( $qdint > $zahl) {echo " minutes"; }
else { echo " minute"; }
var_dump($qdint); //int(91)
var_dump($zahl); //int(100)
?>
Also var_dump says, there are both integer.
But why is there no reaction of is bigger than > (or is smaller than < or is equal to ==)?
Found a working solution, without Timestampdiff:
$result_all = mysql_query("SELECT * FROM sms WHERE gesendet ='1' AND DATE_FORMAT( aktualisiert, '%Y' ) = '2015' AND trash ='0' ORDER BY aktualisiert DESC");
(because a known problem dev.mysql.com...12.7...user comment from April 9 2004
<?php $now = time();
$lastLogin = strtotime($row['aktualisiert']);
$diff = $now - $lastLogin;
$now = date('YmdHis',$now);
$diffecho = idate('i',$diff);
if($diff > 59 && $diff < 119) { // 3600 seconds is 1 hour
echo $diffecho." minute ago"; }
else { echo $diffecho." minutes ago"; }
?>
Use the PHP function idate, if you don't want a leading zero.
There is also another cool way on developphp.com:
Convert MySQL Timestamp to Ago Time Format OOP Tutorial
Maybe I use this later.
Thanks

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}'

"Time ago" from MySQL timestamp

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>

Categories