I'm working on a time management system and am currently stuck. I'm trying to use PHP to calculate the number of hours/minutes between two columns (from and to). These are both set as 'time' type so MySQL recognises it as a time datatype.
I've tried the following in PHP:
$from= isset($_GET['from']) ? '%'.$_GET['from'].'%' : '';
$to = isset($_GET['to']) ? '%'.$_GET['to'].'%' : '';
$diff = $to - $from;
echo "<table border='1'>
echo "<tr>";
echo "<td>" . $row[$diff] . "</td>";
echo "</tr>";
echo "</table>";
Say for example 'to' is set at 15:00:00 and from is set at 09:00:00, then the time difference for that row should be 6 hours and this should be displayed for that row.
The variable $difference is supposed to echo the difference in hours/minutes but it just displays the id assigned to that row instead. I'm trying to echo the number of minutes for each row in the table not just one.
I've seen the timediff function but don't know if that will do the trick.
I don't see your logic with the % and the $_GET vars, and $row suddenly appears out of nowhere.
You should convert the inputted times to php DateTime classes.
An example shows calculating diffs: http://nl1.php.net/manual/en/class.datetime.php#108970
Create your DateTime for example like this:
$dateFrom = new DateTime("2014-02-24 ".$_GET['from']);
$dateTo = new DateTime("2014-02-24 ".$_GET['to']);
$diff = $dateFrom->diff($dateTo);
print_r($diff) ;
The day you use is not really important if you only need the difference in time.
Related
I have been trying to figure this out for a week now. My wife has started a new taxi-company and she asked me to code a simple webpage for here where she could press a button to save a timestamp, then the press is again when she gets off work, it then creates a second timestamp
I have an MYSQL database with rows containing the start time and stop time. I have managed to use the diff function to see how much time it is between the two timestamps but now comes the tricky part.
Since it's different payments at different times of the day I need to divide the time at a shortened time.
Up to 19:00 she works "daytime" and after that, she works "nighttime" until 06:00 the other day, then there is "weekend daytime" and "weekend nighttime" as well.
So if she creates a timestamp whit the date and time: 2018-08-08 06:30 and then another timestamp at 2018-08-08 21:00, then I need a script that puts these data in ex "$daytimehours = 12" "$daytimeminutes = 30" and "$nighttimehours = 3" "$nighttimeminutes = 0"
I have managed to create a script that almost works, but it is several pages long, and it contains one if-statement for each different scenario daytime-nighttime, nighttime-daytime etc.
So do anyone has a good idea on how to solve this? or maybe just point me in the right direction. I would be happy to pay some money to get this to work.
My solution is
<?php
date_default_timezone_set('Asia/Almaty');
$endDate = '2018-08-08 21:00';
$startDate = '2018-08-08 06:30';
$nightmare = date('Y-m-d 19:00');
$startDay = date('Y-m-d 06:00');
$diffMorning = strtotime($nightmare) - strtotime($startDate);
$diffNight = strtotime($endDate) - strtotime($nightmare);
echo gmdate('H:i', $diffMorning) . "\n"; // this is the difference from start day till 19:00
echo gmdate('H:i', $diffNight); // this is the difference on nightmare
$total = $diffMorning + $diffNight;
echo intval($total/3600) . " hours \n";
echo $total%3600/60 . " minutes \n";
echo $total%3600%60 . ' seconds';
You can check via online compiler
given two dates stated as:
$endDate = '2018-08-08 21:00';
$startDate = '2018-08-08 06:30';
you can use the PHP Date extension to achieve the difference like this:
$start = date_create($startDate);
$end = date_create($endDate);
$boundnight = clone($end);
$boundnight->setTime(19,00);
$total_duration = date_diff($end,$start);//total duration from start to end
$day_duration = date_diff($boundnight,$start);//daytime duration
$night_duration = date_diff($end,$boundnight);// nighttime duration
you can use the format method to print a human readable string this way:
$total_duration=$total_duration->format('%H:%I');
$day_duration=$day_duration->format('%H:%I');
$night_duration=$night_duration->format('%H:%I');
At this step there is nothing left but you say you want to convert each duration in minutes.So let's build a function :
function toMinute($duration){
return (count($x=explode(':',$duration))==2?($x[0]*60+$x[1]):false);
}
Then you can use it this way:
$total_duration = toMinute($total_duration);
$day_duration = toMinute($day_duration);
$night_duration = toMinute($night_duration);
The output of
var_dump($total_duration,$day_duration,$night_duration) at this step is:
int(870)
int(750)
int(120)
I'm a very rookie programmer when it comes to PHP. I can usually manage most problems that I run into, but with this one I'm stumped.
I'm trying to create a program where a user can insert a name into a table, and 30 minutes after insertion the name would be flagged as "expired". I'm able to create the row in MySql and using MySql I can put the time when the name was entered. Now what I'm trying to do is take that time from the database and check if it's been 30 minutes since it was entered.
I figure I could do this by taking the time from the database, adding 30 minutes to it, then checking against the current time to see if its past it yet.
This is what I have so far. The time is in this format: 2013-08-21 13:18:35
$result = mysqli_query($con,"SELECT * FROM list ORDER BY id desc");
//snip snip
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['reason'] . "</td>";
echo "<td>" . $row['date'] . "</td>";
cho "</tr>";
}
Now I know that I need to take $row['date'] and add 30 minutes to it. I've read probably about 20 different pages about this, but nothing I do seems to work.
I've seen a few different things suggest such as date_add() and strtotime but either I'm doing something wrong, or it doesn't work.
If I could just get a working code sample for how to add 30 minutes to $row['date'], I'm sure I could explain it to myself.
I know how to compare the two once I've got the 30 minutes added, and I think this would be correct:
if ($time30 < $now) {
// Code to execute
}
Any help would be appreciated.
Considering that $row['date'] prints out 2013-08-21 13:18:35. you need to use strtotime() to convert that value into a timestamp.
See documentation here strtotime.
Now that you have a timestamp, you simply add 1800 seconds to it (half an hour) and you obtain what you need.
Then, a simple comparison between your time and now (you obtain the value with time() ) will give you the result.
This code is a mere example (even too much detailed, because it can be shorter):
$db_time = strtotime("2013-08-21 20:18:35");
$half_hour = 1800;
$time = $db_time + $half_hour;
if($time < time()) echo "expired"; else echo "active";
First, avoid select *
Mysql solution would be to return the time after 30 mins as a column
SELECT TIMESTAMPADD(MINUTE,30,date1);
Assuming date1 is your column name avoid using date as a column name, at best its a maintenance issue
In PHP:
$time30 = strtotime($row['date']) + (30 * 60);
$now = time();
In MySQL
SELECT *,timestampadd(minute,30,date)<now() as expired FROM list ORDER BY id DESC
Then in the PHP you have $row['expired'] as a 1 or 0.
this is my events script that pulls out appointments for the next 7 days, it appears to work ok, but only under one condition........The dates and times are held in the mysql db in datetime format so 2013-12-23 08:30:00 . My script prints out each day and finds appointments for that day for customers that are dropping off or picking up things. The mysql looks through the db and matches the customers with the dropping off or picking up fields to the date being printed and adds them in the div below the date.
The problem I am having is that if the time is set to anything other than 00:00:00 it doesn't pickup that customer for that day. How do I get the comparison to ignore the time and only use the date ?.
// Date box container
echo '<div class="dateboxcontainer">';
// Loop through and create a date for the next 7 days
$days = new DatePeriod(new DateTime, new DateInterval('P1D'), 7);
foreach ($days as $day) {
echo '<div class="datebox">';
echo '<div class="topdate">';
echo strtoupper($day->format('D d')) . PHP_EOL;
echo '</div>';
// Get the names for each day
$theday = strtoupper($day->format('Y-m-d'));
$sqldate = <<<SQL
SELECT *
FROM `jobdetails`
WHERE datedroppingoff = '$theday' OR datepickingup = '$theday'
SQL;
if(!$resultdate = $db->query($sqldate)){
die('There was an error running the query [' . $db->error . ']');
}
while($rowdate = $resultdate->fetch_assoc()){
echo $rowdate['name'];
}
//
echo '</div>';
}
echo '</div>';
//
What you are doing right now is comparing date/time values to just date values. This comparison would fail if the time part is anything other than midnight.
You can fix the comparison by using the DATE() MySql function to compare apples with apples:
WHERE DATE(datedroppingoff) = '$theday' OR DATE(datepickingup) = '$theday'
There are other ways to do the same, for example
WHERE DATEDIFF(datedroppingoff, '$theday') = 0 OR ...
If you had a $nextday value at hand you could also do
WHERE (datedroppingoff >= '$theday' AND datedroppingoff < '$nextday') OR ...
You are storing a specific time and day in mySQL, but only search for a date in your SQL query. As mySQL does not understand the difference between you wanting to search for a complete day or a specific point in time, mySQL assumes you are looking for the day at time 0:00:00.
You have a few options, you could search for a time period (pseudo code, check the borders yourself):
WHERE datedroppingoff > '$theday' AND datedroppingoff < '$theday'+1
another option is to store the date and time in separate db fields. That way you can keep your SQL queries simpler.
Good luck.
I want to write an IF statement based on two dates.
I have a MySQL database (of which I have no control over) for tests and exams taken.
One of the fields is labelled ClientTime and outputs the date and time the test was taken. When queried the typical output would read as such Thu Aug 25 16:47:05 GMT+0100 2011
The following all happens in a while loop
I’ve managed to convert this MySQL date using strtotime() to a d/m/Y format so the above would read 25/08/2011 and I can display a table with all the correct dates.
I also have a php form that asks for the number of days that this test will expire after and this gets stored in a variable $IMonths (from the $_POST['IMonths'] passed from the form page) - the php code will be changed to Months once I have it working but I am using days for the purpose of testing – hence the variable passed being called $IMonths.
I have also created a $today = date("d/m/Y"); variable
I can successfully create a new date using the following command $Expiry = date('d/m/Y', strtotime($row['ClientTime'] . "+$IMonths days")); and can display all results with both the test date and the expiry date.
I then want to include an if-statement within my while-statement that says is ($Expiry>$today) but it’s not accurate – there are no errors and changing the number of days changes the results.
My test database has 5 exams in with the following dates.
Taken 17/08/2011
Taken 17/08/2011
Taken 22/08/2011
Taken 22/08/2011
Taken 24/08/2011
If I set the expiry days to 1, I get all results back as expected:
If I set it to 10 days I get two results
Taken 17/08/2011
Taken 17/08/2011
I don’t get any of the others even though their date will be less than today's date (07/09/2011 (as I write this)) but they do expire in the month of September.
If I set the expiry days to 15, I get one result that is one day in the future!
Taken 17/08/2011
I hope that makes sense. My code is as follows:
<?php
// Make The MySQL Server Connection
mysql_connect("localhost", "root", "") or die(mysql_error());
// Make The MySQL Database Connection
mysql_select_db("questions") or die(mysql_error());
$IQuizName = $_POST['IQuizName'];
$IMonths = $_POST['IMonths'];
$result = mysql_query("SELECT * FROM questions.resultsets
WHERE QuizName='$IQuizName'
AND PassFail='Pass'") or die (mysql_error());
$today = date("d/m/Y");
echo "<table border='1'>";
echo "<tr> <th align='left'>Candidate Name </th> <th align='left'>Pass / Fail</th> <th align='left'>Date last Taken</th> <th align='left'>Expires</th> <th align='left'>Today</th> </tr>";
while($row = mysql_fetch_array($result)){
//START of expiry calculation
$Expiry = date('d/m/Y', strtotime($row['ClientTime'] . "+$IMonths days"));
if($Expiry>$today){
echo "<tr><td>";
echo $row['Candidate'];
echo "</td><td>";
echo $row['PassFail'];
echo "</td><td>";
//Date Conversion
echo date('d/m/Y', strtotime($row['ClientTime']));
echo "</td><td>";
echo $Expiry;
echo "</td><td>";
echo $today;
echo "</td><tr>";
};
}
echo "</table>";
echo "<P>";
?>
Your issue is due to datatypes in PHP. When you call the date() function in PHP, you are actually formatting dates into strings. So when you do $Expiry = date(blahblah), $expiry is now a string. So your if statement is if (somestring > someotherstring). Normally you would not think to compare one block of text to see if it is greater than another block of text.
http://www.php.net/manual/en/function.date.php
One way to get around this would be the strtotime function. This returns integers that are based on UNIX timestamp for the date representation.
http://www.php.net/manual/en/function.strtotime.php
If you convert your string dates to strtotime, your if statement is now comparing if one number is greater than another. This should solve your problem :)
First: fix that SQL-injection hole.
I suggest querying the expiry dates in SQL, it will be much easier.
Here's example code
//escape those user variables !!
$IQuizName = mysql_real_escape_string($_POST['IQuizName']);
$IMonths = mysql_real_escape_string($_POST['IMonths']);
$result = mysql_query("SELECT * FROM questions.resultsets
WHERE QuizName= '$IQuizName'
AND PassFail= 'Pass'
AND ClientTime < NOW() ");
//don't use (or die(error)) in production code, (for now I'll let it slide).
if (!$result) then { die (mysql_error()); }
while ($row = mysql_fetch_row($result))
{
echo "the table"
}
For accurate comparing dates you should convert the dates with the strtotime function again.
In PHP there is no standard date data type. What you have is strings, and when you compare them, they get compared as strings, not as dates, thats why you get results you dont expect. How it normally is done in PHP is to format your date string by ordering from most significant bit to least bit, like
YYYY-MM-DD HH:MM:SS
If you do that, string comparison will work as expected. You can format your dates easily using:
$string = date('Y-m-d H:i:s', $year, $month, $day, $hour, $minute, $second);
I have a date value stored in a variable. I need to extract the time part of the value in to a separate variable and then add/subtract time from it.
The date variable is set with date('YmdHis'), giving (for example) 20110805124000 for August 5th 2011, 12:40:00
From the value 20110805124000 (which is stored in the variable $fulltime), I need to store the time only in the format 12:40 (so ignoring the year, month, day and seconds and adding the colon between the hour and minute) in a variable called $shorttime. I then need to add a number of hours to that time (so for example +3 hours would change the value in the $shorttime variable to 15:40). The number of hours I need to add is stored in a variable called $addtime, and this value could be a negative number.
Is this easily doable? Could anyone help?
Thanks :)
$time = '2013-01-22 10:45:45';
echo $time = date("H:i:s",strtotime($time));
It will give the time 10:45:45 from datetime.
<?PHP
$addhours = 3;
$date = DateTime::createFromFormat('YmdHis', '20110805124000');
$shorttime = $date->format("H:i");
$newdate = $date->add(DateInterval::createFromDateString($addhours . "hours"));
$newtime = $newdate->format("H:i");
echo $shorttime . "<br />";
echo $newtime . "<br />";
?>
for your reference:
http://www.php.net/manual/en/datetime.createfromformat.php
http://www.php.net/manual/en/dateinterval.createfromdatestring.php
hello the way I usually do it is like this, maybe it's a bit long but it works for me...
$DateIn = new DateTime($In);
$DateOut = new DateTime($Out);
$HourOut = new DateTime($H_Out);
$FechaEntrada = $DateIn->format('d-m-Y');
$FechaSalida = $DateOut->format('d-m-Y');
$HoraSalida = $HourOut->format('H:i a');
the guide I used was the PHP one DateTime::format()