Lumen data store as hours minute and second format - php

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

Related

how to calculate time spent on my app by timestamp

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

Inserting actual hours (not time) to MySQL

I am trying to insert actual hours not the time itself to MySQL database through form fields. So for example
$time1 = '00:00';
$time2 = '27:20';
$time3 = '00:45';
So I can retrieve the different rows and can calculate on the fly whenever require. Either through search query or even in other area of the system.
When I have tried to do addition of above three times, it is not giving the result the way I am looking for
$total = strtotime($time1) + strtotime($time2) + strtotime($time3);
echo date('H:i:s', $total);
The result
14:16:44
While it should be something like
28:05:00
I have used TIME DATATYPE in MySQL table. I may use as a TEXT but I am also concern about the error happen in user input. Where I do not have to force the user to insert the any particular format but they can either insert as below way
27.20
27:20
or
1.5
1:30
My main concern is to calculate the time, the user input can be on second priority but it would be great if can implement.
So is there anyway, idea or hint to achieve this?
date() expects the timestamp in UNIX format, i.e. seconds since January 1 1970 00:00:00 UTC (which is also the value provided by strtotime)
You're passing it the result of adding a series of amounts of time since 1 January 1970 instead of just adding up hours, so (as far as date is concerned) you're generating a random date and time, and printing only the time (try printing the date of $total and see what you get).
Since your time is stored in the database, one possibility is to let MySQL handle the time calculations itself, e.g.:
SELECT ADDTIME('00:00',ADDTIME('27:20','00:45'))
will result in "28:05:00". You can have your database fields as TIME and operate on them directly through SQL, and do the user input conversions into acceptable TIME values in PHP.
If you're only interested in the hours and minutes, why don't you just store the value as an in integer? Just multiply the hours by 60.
You can handle the conversion in PHP.
Alternatively, you can also easily use two (very small) int fields for this.

PHP Script to Add One Every Hour

I'm new to PHP and I'm hoping to make a script where a user will get a "coin" every hour that they go on the page. For instance, if a user logs in twice during the same hour, they will only get one coin. But if they refresh the page during the next hour, they get another coin. However, they do not get coins when they do not refresh the page, even if many hours go by.
How would I even start going about doing this? Any help would be extremely appreciated.
Easy... :) If you are using MySQL or something to store the coins, get the time too, when the coin was credited. And each time the page is called, check the time. A pseudo code would be like this:
load(coins);
timeDiff = timeNow - timeLastCredited;
if (timeDiff > 1 hour)
coins++;
save(coins);
In case of PHP, I guess you may do like this:
$coins = getCoins(); // Assuming this function will load the current coins count from DB.
$lastCredit = getLastCoinCreditedTime(); // Should return a DateTime integer.
$timeDiff = microtime() - strtotime($lastCredit);
if ($timeDiff > 60*60*60*1000)
saveCoins($coins+1); // Assuming this function saves the new number of coins.
I'd do it this way:
On each page load (refresh, login, whatever), check to see if the user has already received a coin for the current hour. To do this, you need to know what the current hour is:
$hour = (new DateTime())->format("Y-m-d-h");
This will give a value like "2013-03-25-11" during the 11:00 hour. I'm including the date, since we don't to want skip giving a coin in, say, the 11 o'clock hour just because they were online yesterday at 11:05.
Then you can either:
Add one to their coin total whenever you have a new $hour value (ie. it's not recorded in your database) and save the $hour value, or
Save the $hour value in the database and count the total number of coins earned with a query like SELECT COUNT(DISTINCT hour) FROM table;
The first approach is useful if they're spending the coins on something (ie. you can add/subtract from their "coin account"); the second is useful if you just want a grand total of the number of coins (ie. the total number earned, ever).
I'm going to assume that you have a users table in a database.
If that is the case, you can use a column in the database to update the latest time that a user has gone on the page with php and a query on that page. Then you can set up a cron job that runs every hour that will query the users table and see if the user has viewed the page within the last hour. If the user has viewed the page within the last hour, increment the amount of coins associated with that user.

PHP DateTime Subtraction and Conversion

It's hard to articulate the problem I'm having in the title, but here's the scenario: I'm working the backend of a 3-tiered exam taking website. I'm currently updating my function used for when students request an exam. The exam has start and end dates and times, as well as a time limit. What I want to do is specific to the case when the amount of time left in the exam period is less than the time limit for the exam, For example, the exam period ends at 5:00PM. The time is now 4:30PM. The exam time limit is an hour and a half. I want to replace the hour and a half time limit with 30 minutes. To do that, there are 3 dates I need, and I will explain how I get each:
Timestamp for my function page. When the controller calls my page, after I open the session, I set the default timezone to America/New York (my region). To get the timestamp, I use the code:
$date = date('Y-m-d H:i:s');
$currenttime = date('H:i:s', strtotime($date));
I use a function call to my database to acquire the time limit and the time the exam ends (I also use the dates for other comparisons to check exam availability). The exam end time is stored in resultant array $res[10] and the time limit is in $res[11].
Assuming the due date for the exam is equal to the date of the timestamp, and it is in the exam period (2 checks I perform before), I want to check if the difference between the current time and the end of the exam is less than the time limit. If the time until the exam ends is less than the time limit, I want to set that amount of time as the new time limit. My front end expects my result in the form HH:mm:ss (php's equivalent is H:i:s). So if there is 30 minutes until the exam ends and the time limit is an hour and a half, I want the new time limit to be 30 minutes (or 00:30:00). My code is currently not working as desired. I am meeting the criteria for the if statement, which is my desired result. When I am converting it to the form H:i:s is where the problem seems to be (I keep getting a result around 19:00:00). Every article I've read suggests to do it this way, but I may be missing something.
$compareTime = strtotime($res[10]) - strtotime($currenttime);
if(compareTime < strtotime($res[11]){
$timelimit = date('H:i:s', $compareTime);
}else{
$timelimit = $res[11];
}
If there is a better way of doing this, I'd be much obliged to know. I'm fairly new to php, and admittedly I realize this may be a strange problem, but that's the way the group decided to go.
Maybe it's because the databse and PHP server are using different timezones. Check it out by printing these variables to see their values.

Converting seconds into period of time (PHP)

I have a bug reported whereby the user selects a date frame from a dropdown, hours, days, months and enter a freetext number.
When it's saved this is converted to a number of seconds.
I need to display this field as currently it's not being displayed. How can I work out how to make it into the same value they entered? We do not store the value of the dropdown for some strange reason.
Is there a way to just convert it to the maximum number of time block available for that number of seconds, or shall I just store the dropdown field, which is what I'm likely going to do.
Converting is not an option, since you don't know anything about what the user meant. For example, when I input the number '3', you can't determine if I meant 3 days or 3 months.
Let me elaborate a bit: if I input '3' and select 'days', the time in seconds is: 60 * 60 * 24 * 3 = 259200 seconds. When displaying, you could divide it so that the output is '3 days' again. But what if I inputted '72' and selected 'hours'? You can't tell.
Just store the users choice and you're fine.
If you are looking to split it into chunks dependent such as days/months fairly simple maths operations inside a block should do the trick.
if($seconds > 2629743){
// code for month
}
elseif ($seconds > 86400) {
// code for days
}

Categories