php time messed up - php

i need help creating a count down timer in php.
the problem is that i want to store an INT in my database which is going to be seconds,
and this int is going to be added to current time to represent the future time.
now if i try to subtract the current time from future time to show how many seconds remaining, am getting wrong date.
here is my schema
mysql> desc buildings;
+-----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(20) | YES | | NULL | |
| level | int(2) | YES | | NULL | |
| created | int(11) | NO | | NULL | |
| finished | int(11) | YES | | NULL | |
| player_id | int(11) | YES | MUL | NULL | |
| position | int(2) | YES | | NULL | |
+-----------+-------------+------+-----+---------+----------------+
and heres the code to check
//starting session;
//connecting to database;
$query = "select created, finished from buildings where id = 1";
$query = mysql_query($query) or die ("could not query ".mysql_error() );
while($row = mysql_fetch_assoc($query))
{
$created = $row['created'];
$finished = $row['finished'];
}
$CurrentTime = time();
$status = $finished - $CurrentTime;
$realstatus = date("H:i:s",$status);
if($status > 0)
{
echo "under construction, still ".$realstatus." to finsih";
}else
{
die("construction complete");
}
//echo $created."".$finished;
?>
any help will be greatly appreciated.

Can't offer much of an answer without seeing your code, but maybe this will provide some insight:
<?php
$fmt = 'Y-m-d H:i.s'; // date formatting
$now = time(); // current time
$offset = 600; // future offset
$future = strtotime('+' . $offset . ' seconds'); // future time using relative time
$timeleft = $future - $now; // time left in seconds
// echo results
echo 'Current Time: ' . date($fmt, $now) . PHP_EOL;
echo 'Event Time: ' . date($fmt, $future) . PHP_EOL;
echo 'Time Until Event: ' . $timeleft . ' seconds' . PHP_EOL;
?>
Output:
Current Time: 2011-05-03 12:00.15
Event Time: 2011-05-03 12:10.15
Time Until Event: 600 seconds

Your problem is that you are subtracting two timestamps and format the result as a date. The result is not a date, it´s an interval between two dates.
If you want to know how many hours / minutes / seconds are remaining, you just have to divide your result $status through 3600 / 60 / 1 (divide for hours and take the remainder to divide for minutes etc.).

Related

calculating time attendance in PHP MySQL

I am working with laravel and i have a table with all the users attendances.
each row has a flag stating if the user logs in or out. I want to calculate the total working hours of user.
this is my table and sample data
id | user_id | date | timestamp | status |
1 | 1 | 2018-05-10 | 17:15:31 | out |
1 | 1 | 2018-05-10 | 13:15:31 | in |
1 | 1 | 2018-05-10 | 12:15:31 | out |
1 | 1 | 2018-05-10 | 08:01:31 | in |
I want to calculate the total working hours
$logs = DB::table('attendances as at')
->join('infos as in','in.user_id','=','at.user_id')
->select('in.name','in.avatar','at.*')
->orderBy('id','desc')
->where('at.user_id',$id)
->get();
$total_hours = [];
for($i=0; $i < count($logs)-1; $i++ ){
if($logs[$i]->status == 'out'){
$dattime1 = new DateTime($logs[$i]->dt.' '. $logs[$i]->time);
$dattime2 = new DateTime($logs[$i+1]->dt.' '. $logs[$i+1]->time);
$total_hours[] = $dattime1 ->diff($dattime2);
}
}
$working_hours = array_sum($total_hours);
Is this the best way to achieve accurate results? Please help.
Thanks
Can you try like this?
$time1 = "17:15:00";
$time2 = "00:30:00";
$strtotime1 = strtotime($time1);
$strtotime2 = strtotime($time2);
$o = ($strtotime1) + ($strtotime2);
echo $time = date("h:i:s A T",$o);
Output will be like this:
05:45:00 PM UTC

How to determin date below todays date from db in php

I'm developing a pharmacy store project, but I have a problem of determining the total number of drugs that expired. From DB I have:
+----+----------+--------+------------+
| id | drug_nam | amount | exp |
+----+----------+--------+------------+
| 1 | M and T | 200 | 04/15/2016 |
| 2 | VIT C | 20 | 05/25/2016 |
| 3 | Pana | 10 | 01/03/2016 |
| 4 | Lonat | 1200 | 08/25/2017 |
| 5 | ProC | 100 | 05/25/2017 |
+----+----------+--------+------------+
what I need here is a line of PHP script that will count the numbers of expired drugs from DB. using <?php $d = date('m/d/Y'); ?> to determine it from DB.
I used the code below but it count only 2
<?php
$d = date('m/d/Y');
$result = mysqli_query($conn, "SELECT count(exp) FROM products where exp < $d ");
while($row = mysqli_fetch_array($result))
{
echo $row['count(exp)'];
}
You should convert your string date representation to date value if you want to filter by date but not by string.
This query should work:
SELECT count(exp) FROM products where STR_TO_DATE(exp, '%d/%m/%Y') < $d
The main drawback is mysql can't use index in this case. One of the solution is to convert your column from varchar(50) to DATETIME. In this case you can use your original query.
From your table it seems you used some sort of text or varchar for you exp column. Cause mysql date format should be like yyyy-mm-dd. Please change your exp column to date and change the below line
$d = date('m/d/Y');
to
$d = date('Y-m-d');
That should be good.

Displaying daily totals between now and x days ago using MYSQL/PHP

I have a table called 'orders' and it contains; id, order_total and time fields. 'time' is an integer and stores a unix timestamp...
orders
| id | order_total | time |
-------------------------------------
| 1 | 42.00 | 1443355834 |
| 2 | 13.00 | 1443460326 |
| 3 | 51.00 | 1443468094 |
| 4 | 16.00 | 1443477442 |
| 5 | 10.00 | 1443606966 |
| 6 | 53.00 | 1443608256 |
I want to able to display in a table using php the sum, of 'order_total' for each day for the previous 'x' amount of days (or weeks or months) so it will look something like this:
| Date | Order Total |
---------------------------
| 27/09/15 | 42.00 |
| 28/09/15 | 80.00 |
| 30/09/15 | 63.00 |
I have made a MYSQL query and a php loop that kind of works but being new to MYSQL I am probably over-complicating things and there must be an easier way to do this ? When I say kind of works, it will correctly sum and show the order_totals up until the current day but for some reason will combine the current day with the previous day.
Here is what I currently have:
$x = $interval;
$y = $x - 1;
while ($x > 0) {
$sql10 = "
SELECT id,
time,
SUM(order_total) as sum,
date_format(DATE_SUB(FROM_UNIXTIME($now_time), INTERVAL $x DAY), '%Y-%m-%d') as thedate
FROM $ordersTABLE
WHERE FROM_UNIXTIME(time) BETWEEN date_format(DATE_SUB(FROM_UNIXTIME($now_time), INTERVAL $x DAY),'%Y-%m-%d')
AND date_format(DATE_SUB(FROM_UNIXTIME($now_time), INTERVAL $y DAY),'%Y-%m-%d')";
$result10 = mysql_query ( $sql10, $cid ) or die ( "Couldn't execute query." );
while ( $row = mysql_fetch_array ( $result10) ) {
$order_total = $row ["order_total"];
$thedate = $row ["thedate"];
$sum = $row ["sum"];
$sum = number_format($sum,2);
$thedate = strtotime($thedate);
$thedate = date("d/m/y",$thedate);
print "<tr><td width=\"120\">$thedate</td><td>\$$sum</td></tr>";
}
$x--;
$y--;
}
(The string $now_time contains the current time as a Unix Timestamp hence the converting as the system time can not be changed and this contains the correct local time for the user)
Is there better way to do this ?
You can convert the timestamps into YYYY MM DD using FROM_UNIXTIME function and then select only the ones which are older enough thanks to the DATEDIFF function. Today's date is provided by CURDATE function.
First of all, the query which retrieves the totals for the orders older then the interval and reformats the date fields:
$q1 = "SELECT " . $ordersTABLE . ".order_total AS total, FROM_UNIXTIME(" . $ordersTABLE . ".time, '%Y-%m-%d') AS short_date FROM " . $ordersTABLE . " WHERE DATEDIFF(CURDATE(), short_date) > " . $intervalInDAYS;
Then, the one that sums up the totals of the day:
$q2 = "SELECT short_date AS day, SUM(total) AS total FROM (" . $q1 . ") GROUP BY short_date";
And then you perform your query stored in $q2 and all other operations you need to display the result.
Result from the query should be in form:
| day | total |
===========================
| 25/09/15 | 34.00 |
| 16/09/15 | 100.00 |
| 31/07/14 | 3.20 |
| ... | ... |

Convert int 60 to a time value of 60 minutes

This seems it should be trivially simple but I can't find the time format I would need.
A value comes from the database as 240. This means 240 minutes. How can I store this in a php variable so that php knows it's minutes. So that later in the script I can add it to a HH:MM value?
(I have edited the code below to reflect one of the answers)
$startTime = new datetime($row['startTime']); #08:07:00.0000000
$endTime = new datetime($row['endTime']); #12:10:00.0000000
$everyMinutes = new dateInterval('P'.$row['everyMinutes'].'M'); #60?
$updatedTime = $startTime->add($everyMinutes); # this should read 09:07:00.0000000
The date coming into $row comes from sql. startTime and endTime are of time(7) datatype
| taskID | startTime | endTime | freq |
|________|__________________|__________________|______|
| 1 | 08:07:00.0000000 | 12:10:00.0000000 | 60 |
| 2 | 08:10:00.0000000 | 17:40:00.0000000 | 30 |
| 3 | 08:40:00.0000000 | 14:49:00.0000000 | 60 |
| 4 | 08:43:00.0000000 | 14:49:00.0000000 | 60 |
| 5 | 09:05:00.0000000 | 15:05:00.0000000 | 180 |
| 6 | 10:00:00.0000000 | 22:00:00.0000000 | 5 |
With this code I am getting one of two issues. With new datetime() the error thrown is Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct() expects parameter 1 to be string, object given'
Without new datetime() the error thrown is Notice: Object of class DateTime could not be converted to int
You should read this page.
$date = new DateTime($row['startTime']);
$myInterval = new DateInterval('P'.$row['everyMinutes'].'M');
$date->add($myInterval);
echo $date->format('Y-m-d') . "\n";
Use this function
function convertToHoursMins($time, $format = '%d:%d') {
settype($time, 'integer');
if ($time < 1) {
return;
}
$hours = floor($time/60);
$minutes = $time%60;
return sprintf($format, $hours, $minutes);
}
and pass your time in this like
convertToHoursMins(240);

why does this code loop twice [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am having an issue trying to pinpoint a problem I am having, the code below loops twice and gives me an output of Match11Match111Match11Match111 I am really not sure where the problem is but it should only loop once.
<?php
function generateTimeCard($conn, $employeeID){
// set current date
$date7 = date("m/d/y");
// parse about any English textual datetime description into a Unix timestamp
$ts = strtotime($date7);
// calculate the number of days since Monday
$dow = date('w', $ts);
$offset = $dow;
if ($offset < 0) {
$offset = 6;
}
// calculate timestamp for the Monday
$ts = $ts - $offset*86400;
// loop from Monday till Sunday
for ($i = 0; $i < 7; $i++, $ts += 86400){
$date1 = date("m/d/y", $ts);
$date3 = date("l", $ts);
$$date3 = $date1;
$date2 = $date1;
$day[$i] = $date1;
$stmt = $conn->prepare('SELECT `employeeID`,`date`,`unitNumber`,`jobDescription`,`timeIn`,`timeOut`, `lunch`, TIMEDIFF(`timeOut`, `timeIn`)
AS `totalTime` FROM `timeRecords` WHERE `date`= :day AND `employeeID`= :employeeID ORDER BY date,id;');
$stmt->execute(array(':day'=>$day[$i], ':employeeID'=>$employeeID));
$dayOW = 1;
while($row = $stmt->fetch()) {
if ($row['lunch'] == "Yes"){
echo "Match";
} else{
echo "1";
}
$dayCurrent = $date3 . "Hours." . $dayOW;
$data[$dayCurrent] = $row['totalTime'];
$timeDay = $date3 . "." . $dayOW;
$unitNumber = $date3 . "UnitNumber." . $dayOW;
$description = $date3 . "Description." . $dayOW;
$data[$timeDay] = date("h:i A", strtotime($row['timeIn'])) . "/" . date("h:i A", strtotime($row['timeOut']));
$data[$unitNumber] = $row['unitNumber'];
$data[$description] = $row['jobDescription'];
$dayOW++;
}
$stmt = $conn->prepare('SELECT `employeeID`, SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(`timeOut`, `timeIn`))))
AS `totalDay` FROM `timeRecords` WHERE `date` = :day
AND `employeeID` = :employeeID GROUP BY `employeeID`;');
$stmt->execute(array(':day'=>$date1, ':employeeID'=>$employeeID));
$row = $stmt->fetch();
$totalDay = "Total" . $date3;
$data[$totalDay] = $row['totalDay'];
}
$data['Week']= $Sunday . " - " . $Saturday;
return $data;
}
?>
My database looks like this
+----+------------+----------+--------+----------------------------+-------------+------------+-----------+---------+-------+
| id | employeeID | date | timeIn | jobDescription | equipType | unitNumber | unitHours | timeOut | lunch |
+----+------------+----------+--------+----------------------------+-------------+------------+-----------+---------+-------+
| 1 | 1 | 01/20/13 | 6:00 | Worked in RockPort | Excavator | 01E | 7238 | 17:13 | Yes |
| 2 | 1 | 01/21/13 | 6:00 | Worked in Jefferson | Excavator | 01E | 7238 | 17:17 | |
| 3 | 1 | 01/22/13 | 6:00 | Worked in Jefferson | Excavator | 02E | 7238 | 17:30 | |
| 4 | 1 | 01/23/13 | 6:00 | Worked in Whispering Creek | Skid Loader | 32SL | 2338 | 18:30 | Yes |
| 5 | 1 | 01/24/13 | 8:00 | Worked in Hubbard | Scraper | 54C | 9638 | 11:30 | |
| 6 | 1 | 01/25/13 | 8:00 | Worked in Jefferson | Dozer | 4D | 941 | 19:30 | |
| 7 | 1 | 01/26/13 | 8:00 | Pushed Snow | Loader | 950H | 342 | 20:30 | |
+----+------------+----------+--------+----------------------------+-------------+------------+-----------+---------+-------+
By default, PDO fetches with index and column-name keys. So there are "duplicate" values. You want to change the fetch mode to FETCH_NUM (only index keys) ($stmt->fetch(PDO::FETCH_NUM)) so that values don't appear under two mappings. http://php.net/manual/en/pdostatement.fetch.php

Categories