Convert int 60 to a time value of 60 minutes - php

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

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.

(Symfony 3.1) PHP Doctrine Group entities by datetime

I am stack trying to group my entities by datetime. every entity has the following columns: id, device, start, stop, ipaddress.
I want to be able to get entities within a range of date and group them by date(day) following with how many hours each days has.
This is what i have so far
public function findAllGroupedByDate($from = null, $to = null)
{
$from = isset($from) && !is_null($from) ? $from : date('Y-m-d', time());
$to = isset($to) && !is_null($to) ? $to : date('Y-m-d', time());
$from = new \DateTime("-3 days");
$to = new \DateTime("1 days");
$from = date("Y-m-d", $from->getTimestamp());
$to = date("Y-m-d", $to->getTimestamp());
$q = $this->getEntityManager()->createQueryBuilder()
->select("timelog")
->from("AppBundle:Timelog", "timelog")
->where("timelog.start BETWEEN :from AND :to")
->setParameter("from", $from)
->setParameter("to", $to)
->orderBy("timelog.stop")
->getQuery();
return $q->getResult();
}
public function findFromToday()
{
$q = $this->createQueryBuilder('t')
->select('t.id', 't.start', 't.stop', 't.stop')
->where("t.start >= :today")
->setParameter("today", date('Y-m-d', time()))
->groupBy("t.id", "t.stop")
->orderBy("t.start", "asc")
->getQuery();
return $q->getResult();
}
This is the code for my repository class.
and the code for from my controller looks like this:
$timelogsRepo = $this->getDoctrine()->getRepository('AppBundle:Timelog');
// Grab logs from today
$timelogsCollection = $timelogsRepo->findFromToday();
$tmpLogs = $timelogsRepo->findAllGroupedByDate();
// THIS SECTION IS FOR CALCULATING HOURS & MINUTES
$minutes = 0;
$hours = 0;
foreach($timelogsCollection as $log)
{
$time1 = $log['start'];
$time2 = $log['stop'];
$interval = date_diff($time1, $time2);
$hours += $interval->h;
$minutes += $interval->i;
}
$minutes = $minutes >59 ? $minutes/60 : $minutes;
return $this->render(':Timelog:index.html.twig', [
'timelogs' => $logsOut,
'hours' => $hours,
'minutes' => $minutes
]);
So far i was able to calculate total spent time for a given day(only one day). Now i would like to get alle entities, group them by same date(day) and return data with interval.
Example DB table looks like this[id, device_id, start, stop, ipaddress]
1 1 2016-08-09 09:00:06 2016-08-09 12:00:06 127.0.0.1
2 1 2016-08-08 07:00:00 2016-08-08 13:00:00 127.0.0.1
3 1 2016-08-08 13:10:00 2016-08-08 15:05:00 127.0.0.1
So in this case my output would be something like:
[
0 => ["date" => "2016-08-09", "hours" => 9.00, "ipaddress" => "127.0.0.1"],
1 => ["date" => "2016-08-09", "hours" => 1.45, "ipaddress" => "127.0.0.1"]
]
the interval depends on start and stop both are type of DateTime
I have tried using doctrine-extensions: oro/doctrine-extensions but now i am getting exception error:
[2/2] QueryException: [Syntax Error] line 0, col 50: Error: Expected Unit is not valid for TIMESTAMPDIFF function. Supported units are: "MICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR", got 'stop'
My repository method looks like this:
public function findByToday()
{
$fields = array(
'DATE(stop) as stop',
'TIME(SUM(TIMESTAMPDIFF(stop, start))) AS tdiff',
'device_id',
'ipaddress'
);
$q = $this->createQueryBuilder('t')
->select($fields)
->where('DATE(stop) = :today')
->setParameter('today', date('Y-m-d', time()))
->groupBy('device_id')
->getQuery();
return $q->getResult();
}
my DB table:
id device_id start stop ipaddress
5 1 2016-08-09 09:00:06 2016-08-09 12:00:06 127.0.0.1
6 1 2016-08-08 07:00:00 2016-08-08 13:00:00 127.0.0.1
7 1 2016-08-08 13:10:00 2016-08-08 15:05:00 127.0.0.1
BTW i am using Symfony 3, could that be the problem?
Based on your table above (if I got it right) I would try to get the data directly with MYSQL and then work my way to Doctrine.
If you have the below table:
CREATE TABLE `testdevices` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`device` INT(11) NULL DEFAULT NULL,
`dstart` DATETIME NULL DEFAULT NULL,
`dend` DATETIME NULL DEFAULT NULL,
`ip` TINYTEXT NULL,
PRIMARY KEY (`id`)
);
And populated with below test data (I've created two devices the second one was conveniently active for exact 3 hours on today's date):
mysql> select * from testdevices;
+----+--------+---------------------+---------------------+-----------+
| id | device | dstart | dend | ip |
+----+--------+---------------------+---------------------+-----------+
| 1 | 1 | 2016-08-09 09:00:06 | 2016-08-09 12:00:06 | 127.0.0.1 |
| 2 | 1 | 2016-08-08 07:00:00 | 2016-08-08 13:00:00 | 127.0.0.1 |
| 3 | 1 | 2016-08-08 13:10:00 | 2016-08-11 22:14:46 | 127.0.0.1 |
| 4 | 2 | 2016-08-11 13:00:00 | 2016-08-11 14:00:00 | 127.0.0.1 |
| 5 | 2 | 2016-08-11 15:00:00 | 2016-08-11 16:00:00 | 127.0.0.1 |
| 6 | 2 | 2016-08-11 17:00:00 | 2016-08-11 18:00:00 | 127.0.0.1 |
+----+--------+---------------------+---------------------+-----------+
6 rows in set (0.00 sec)
Following MYSQL query will then I believe output the data you want:
SELECT DATE(dend) as dend, TIME(SUM(TIMEDIFF(dend, dstart))) AS tdiff, device, ip
FROM testdevices WHERE DATE(dend) = '2016-08-11'
GROUP BY device ;
And the result would look like this:
+------------+----------+--------+-----------+
| dend | tdiff | device | ip |
+------------+----------+--------+-----------+
| 2016-08-11 | 81:04:46 | 1 | 127.0.0.1 |
| 2016-08-11 | 03:00:00 | 2 | 127.0.0.1 |
+------------+----------+--------+-----------+
2 rows in set (0.01 sec)
Note that second device time is correct. Now, the remaining question is how to do that in Doctrine. As far as I know the TIMEDIFF function is not a part of Doctrine yet so I would propose 2 different approaches:
Write your own function as in
http://www.doctrine-project.org/2010/03/29/doctrine2-custom-dql-udfs.html#date-diff (There is example of DATEDIFF in this link so it is easily adjustable), or
Use https://packagist.org/packages/oro/doctrine-extensions
Your final repository function in Doctrine/Symfony2 with oro/doctrine-extensions installed would look something like this:
$fields = array(
'DATE(dend) as dend',
'SUM(TIMESTAMPDIFF(SECOND, dend, dstart)) AS tdiff',
'device',
'ip'
);
public function findFromToday()
{
$q = $this->createQueryBuilder('t')
->select($fields)
->where('DATE(dend) = :today')
->setParameter('today', date('Y-m-d', time()))
->groupBy('device')
->getQuery();
return $q->getResult();
I wrote this function without testing it at all and from the top of my head. You will probably find that it fails. This would give the time difference in seconds as the TIMESTAMPDIFF requires units to be specified.
Install oro/doctrine-extensions with
composer require oro/doctrine-extensions

Querying MySQL Timestamp in PHP

I'm querying the timestamp from the field created in the table messages.
My database table currently stands as..
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
| msg_id | messages | uid_fk | ip | created | uploads |
| 706 | ........ | 39 | .. | 1368631445 | 0 |
| 717 | ........ | 39 | .. | 1368640802 | 0 |
| 705 | ........ | 39 | .. | 1368631238 | 0 |
| 696 | ........ | 39 | .. | 1368595705 | 0 |
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
This is how I'm querying the timestamp from created.
public function Time_Stamp($uid){
$res = mysql_query("SELECT created FROM messages WHERE uid_fk='$uid'");
while ( $row = mysql_fetch_array($res) ) {
echo date("g:i", strtotime($row["created"])) . "<br />";
}
}
----- Output -----
9:00
9:00
9:00
9:00
So basically just printing out in a list the same time.
It's not printing their unique time from the created field. I'm not so perfect with MySQL but It has do to with their unique iD's(either msg_id, uid_fk) also, $uid equals the uid_fk, $uid is defined in another table.
How do I go about bringing their specific iD's to print out their correct timestamp.
echo date("g:i", $row["created"]);
strtotime turns a date string like 2013-05-15 22:35:00 into a timestamp.
date turns a timestamp into a readable date string.
You already have timestamps in the database, don't use strtotime.

php time messed up

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.).

Categories