i have one column timestamp when user enters the app and another column when user leaves the app . i want to calculate the time spent on the app :
sum(timestamp_exit) - sum (timestamp_enter) .
right now i've tried to right the current query :
select (SUM(unix_timestamp(`created_time_enter`))) as enter , (SUM(unix_timestamp(`created_time_exit`))) as exit
FROM `my_table`
but i get large numbers and i don't know if it's the correct way. any suggestion?
You could calculate this using the timeDiff function:
times = array();
foreach ($result as $row){
// convert to unix timestamps
$firstTime=strtotime($firstTime);
$lastTime=strtotime($lastTime);
// perform subtraction to get the difference (in seconds) between times
$timeDiff=$lastTime-$firstTime;
$times[] = $timeDiff;
echo(secondsToTime($timeDiff));
# 18 days, 23 hours, 41 minutes and 7 seconds
}
echo(secondsToTime(array_sum($times)));
#total of all times
Related
I am trying to write a php solution to calculate the planned end time considering the target in business hours.
It shouldn't consider some days (retrieved from setting saved in db) such as holidays.
Also business hours are retrieved from db (morning_from (8:30am), morning_to (1:00pm), evening_from (2:30pm), evening_to (6:30pm)).
I want to develop this script because I want that my page shows the remaining time for technical resolution of an opened ticket every day.
For example:
customer having contract with 10 working hours SLA opens a ticket
today (friday) 31/01/2020 16:00:00, considering that in the
noBusinessDays = array("saturday", "sunday") and businessHours set as mentioned before(8:30-13:00/14:30-18:30), the result will have to
be monday 3/02/2020 17:30:00.
Code example:
$noBusinessDays = array("saturday", "sunday");
$businessHours = array("morning_from" => "8:30", "morning_to" => "13:00", "evening_from" => "14:30", "evening_to" => "18:30");
$SLA = "10"; //hours
$ticketDate = new DateTime();
$ticketDate->setTimestamp(strtotime("31/01/2020 16:00:00"));
// I don't know how to use my arrays to say in this calculation how to use them
$maximumLimit = $ticketDate->add(new DateInterval("PT" . $SLA ."H"));
Thank you in advance.
You may use the following function
// intersection of 2 time intervals
// input - Unix timestamps (start,end)
// output - intersection in seconds
function time_union($b_1,$e_1,$b_2,$e_2)
{
return max(0,$e_1-$b_1 - max(0,$e_1-$e_2) - max(0,$b_2-$b_1));
}
You will start with an empty time interval [X, Y) where X is the timestamp of the ticket creation and Y initially is equal to X.
Then you start adding days to Y - one by one. Each time you expand the time interval to contain another day - you use the above function to check how much of the SLA hours are covered (i.e. overlapping) with the working hours in the day you have just added. If the day is marked as a holiday - you simple skip it and continue with the next date.
If you find out that SLA hours are partially covered with either the morning or evening business hours - you should simply subtract the extra hours.
In the end Y will be equal to the timestamp that you want to show in your application.
I think I'd break down the problem into pieces. After calculating the total number of days in the interval, first dispose of the trivial case that it's all happening in one week.
begin by calculating the number of "whole weeks." Each "whole week" is five business days. Subtract the corresponding interval of time and proceed. Now, look at the day-of-the-week of the start-date: each day adds a certain number of days. Then the day-of-week of the end date, likewise. You can then consider hour-of-the-day as needed.
Holidays are a simple table: if the day falls within the range, subtract one day.
Now ... having said all of that, the very first thing that I would do is to search GitHub and SourceForge! Because I am extremely sure that somebody out there has already done this. :-D
"Actum Ne Agas: Do Not Do A Thing Already Done."
I'm using Lumen to build an API. At first, I want to explain my work a little
bit. My API will provide an content to a user. The user will record the content
and submit it with audio length. (EX: 1min. 22 sec.)
I just store it in my
database. when the user wants to see how many hours he recorded I will return
the total time. okay... that's why i was created a table column
$table->decimal('audio_length');
and store it how user sends request. when the user wants to see the total
time my code will work like:
$point = PointSpeech::where('user_id', Auth::user()->id)->get();
$total_point = 0;
foreach ($point as $value) {
$total_point += $value->points_pending;
}
return response()->json(['status'=> 'Success', 'point_pending' => $total_point], 200);
yeah I know it's a stupid way. Now I looking for a better way to show it as
Hour, Minute and Second. hi, can you guys help me...? please...?
When you're storing the duration in this way, you should always convert to the smallest unit you want to record. In your case, if you don't care about milliseconds (or smaller), you should convert the time given by the user to seconds e.g. 1 minute 22 seconds, would be 82 seconds.
This is the number you should store in the database. If you do care about smaller units such as milliseconds, then that is what you should store in the database. Store an integer value.
Now when pulling your information out of the database, you can do a simple SUM to get the total number of seconds (or milliseconds) and convert that back to display to the user.
Converting to hours, minutes and seconds should be easy enough to do once you have an integer representing seconds. As an example:
$seconds = 176; // This would come from your database query
echo (new DateTime('#0'))
->diff(new DateTime("#$seconds"))
->format('%h hours, %i minutes and %s seconds');
What i want is simple, i have timestamp in my mysql database that records date and time data registers. What i want is to calculate the timediff between timestamp and current time then subtract from 3hours to know time remaining in hh:mm:ss format, please someone help out.
You should use the following part in your query:
SELECT TIME_FORMAT(SEC_TO_TIME(AVG(TIMESTAMPDIFF(SECOND, NOW(), column_with_date_to_compare))), '%H:%i')
You must skip the AVG part if you do not want averages but a result per row (or you have only one row to check) (or use GROUP BY [something])
The part 'then subtract from 3hours', I don't understand. You only want to show the records where the time is less than 3 hours? Just use WHERE TIME(record_to_check) > (NOW() - 10800).
If you want to add, calculate or do other things to influence the result, just do so before SEC_TO_TIME, you can do the math (with seconds) there.
I've interpretted your question as how to calculate the time remaining in a 3 hour period starting at a datetime stored in a DB, to be displayed in HH:MM:SS format...
I generally find it easier to manipulate dates / times in php rather than wihtin an SQL query. So my approach would be to:
read strings from the database
convert them into unix timestamps (ie
number of seconds elapsed since a given epoch)
manipulate them mathematically (ie add on 3 hours and subtract the curent time)
lastly convert the result back into a date / time in your chosen
format.
Assuming $start_str has been read from your DB
$start_str = '08-03-2017 11:10:00';
$start_ts = strtotime("$start_str");
$end_ts = $start_ts + (3 * 60 * 60);
$now_ts = strtotime('NOW');
$remaining_ts = $end_ts - $now_ts;
$remaining_str = ($remaining_ts > 0)? sprintf('%02d:%02d:%02d', ($remaining_ts/3600),($remaining_ts/60%60), $remaining_ts%60) : "None, time's up";
echo ($start_str.'|'.$start_ts.'|'.$end_ts.'|'.$now_ts.'|'.$remaining_ts.'|'.$remaining_str);
Examples...
08-03-2017 11:10:00|1488971400|1488982200|1488983863|-1663|None, time's up
08-03-2017 14:30:00|1488983400|1488994200|1488983982|10218|02:50:18
Obviously in reality you're only interested in the last field, but the others show you what you're playing with during the process.
I am working on a project where one "lights a virtual candle" and I want to create a cron job that selects all records from the database that are expiring in the next five days, possibly calculated from the databases "created_date" field which type is "Type: TIMESTAMP > CURRENT_TIMESTAMP"
Process:
The candle duration = 30 days
Alert period = 5 days before the 30 days
This is what I have so far (I can do the rest, it is the query I am having problems with)
$query_rsQueryA = "SELECT * FROM $databaseName WHERE created_date + INTERVAL 5 DAY < CURRENT_TIMESTAMP;";
$rsQueryA = mysql_query($query_rsQueryA) or die(mysql_error());
$row_rsQueryA = mysql_fetch_assoc($rsQueryA);
$totalRows_rsQueryA = mysql_num_rows($rsQueryA);
Thanks in advance!
It appears what I have written above actually works, should have tried it first guys, sorry about that!
You can use the following
datediff(now(),date_add(created_date,INTERVAL 25 day)) > 0
So basically its adding 25 day to the created_date and then finding the difference with the current date and if its greater than 0 meaning start sending alert
What's the best way to retrieve start_time and end_time times from a mysql db using php and add them together to get a total of hours and minutes? An example military time in my db is: 18:35:19 to 22:05:14. Is it easier with standard or military time? Thanks in advance.
Carlos,
Some further information such format the data is stored within mysql would have been helpful, as there are certain mysql queries to help with this. But seeing as you've tagged PHP, I would do the following in php:
convert the time to unixtimestamp using something like mktime (http://php.net/manual/en/function.mktime.php)
$unixtimestamp_start = mktime($hour,$minute,$second,$month,$day,$year);
$unixtimestamp_finish = mktime($hour,$minute,$second,$month,$day,$year);
minus the start time from the finish time.
$timeDiffSeconds = $unixtimestamp_finish - $unixtimestamp_start;
You now have the amount of seconds between finish and start.
you can divide that by 60 to have minutes
$timeDiffMins = $timeDiffSeconds/60;
you can divide that by 60 again to have hours.
$timeDiffHrs = $timediffMin/60;