php seconds to hours and minutes
Convert seconds into days, hours, minutes and seconds
26 Answers 26
This can be achieved with DateTime class
Function:
This is the function rewritten to include days. I also changed the variable names to make the code easier to understand.
Based on the answer by Julian Moreno, but changed to give the response as a string (not an array), only include the time intervals required and not assume the plural.
The difference between this and the highest voted answer is:
For 259264 seconds, this code would give
For 259264 seconds, the highest voted answer (by Glavić) would give
3 days, 0 hours, 1 minutes and 4 seconds
I hope this helps someone.
Here it is a simple 8-lines PHP function that converts a number of seconds into a human readable string including number of months for large amounts of seconds:
Result will be 19 23:41:07. When it is just one second more than normal day, it is increasing the day value for 1 day. This is why it show 19. You can explode the result for your needs and fix this.
There are some very good answers here but none of them covered my needs. I built on Glavic’s answer to add some extra features that I needed;
Converting seconds to hours/minutes/seconds in PHP [duplicate]
I have an integer as a number of seconds. I want to convert that integer into into hours/minutes/seconds like this:
If the number of seconds equates to less than one hour then it should return the string:
If the number of minutes is less than 10 it should return the string formatted like this:
And finally if the number of seconds equate to less than 1 minute, it should return the following:
What is the best way to do this in PHP?
5 Answers 5
The simpelst approch would be
EDIT: this wouldnt fix your minutes
I think Rufinus is pretty close:
This variant uses a configuration stored inside an array which associates a format string based on a time value in seconds (as key). The last element is the default format that will fall through.
Edit: Unfortunately there is no formatting code in date that allows to specify minutes w/o a leading there. Therefore the date string needs to be re-formatted to remove leading 0’s occasionally. It’s done with ltrim here.
Consider using explode() & implode() and then apply your logic of less-than & greater-than!
Not the answer you’re looking for? Browse other questions tagged php time or ask your own question.
Linked
Related
Hot Network Questions
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Convert seconds to Hour:Minute:Second
I need to convert seconds to «Hour:Minute:Second».
For example: «685» converted to «00:11:25»
How can I achieve this?
28 Answers 28
You can use the gmdate() function:
One hour is 3600sec, one minute is 60sec so why not:
(I’ve not tested this much, so there might be errors with floor or so)
Use function gmdate() only if seconds are less than 86400 (1 day) :
Convert seconds to format by ‘foot’ no limit* :
Example use of DateTime extension:
Input: 6030 Output: 1:40:30
Input: 2000006030 Output: 555557:13:50
Will not give time in H:i:s format if no_of_seconds is greater than 1 day (seconds in a day).
It will neglect day value and give only Hour:Min:Seconds
If you don’t like accepted answer or popular ones, then try this one
Here is a one liner that handles negative seconds and more than 1 day worth of seconds.
write function like this to return an array
then simply call the function like this:
This function my be useful, you could extend it:
Here is a very clean and short method!
This code avoids as much as possible of the tedious function calls and piece-by-piece string-building, and the big and bulky functions people are making for this.
It produces «1h05m00s» format and uses leading zeroes for minutes and seconds, as long as another non-zero time component precedes them.
And it skips all empty leading components to avoid giving you useless info like «0h00m01s» (instead that will show up as «1s»).
Example results: «1s», «1m00s», «19m08s», «1h00m00s», «4h08m39s».
Duration must be 0 or higher in both of the code pieces above. Negative durations are not supported. But you can handle negative durations by using the following alternative code instead:
How do you convert 00:00:00 to hours, minutes, seconds in PHP?
I have video durations stored in HH:MM:SS format. I’d like to display it as HH hours, MM minutes, SS seconds. It shouldn’t display hours if it’s less than 1.
What would be the best approach?
10 Answers 10
Something like this?
One little change could be:
This will only display the hours or minutes if there are any, and inserts an «and» before the seconds if there are hours, minutes, or both to display. If you wanted to get really fancy, you could add some code to display «hour» vs. «hours» as appropriate, ditto for minutes and seconds.
Why bother with regex or explodes when php handles time just fine?
The benefit is that you can reformat the time however you like (including am/pm, adjustments for timezone, addition / subtraction, etc).
Heres a different way, with different functions which is more open and a more step by step for newbies. it also handles the 1 hour and many hours. you could try use the same logic to handle the 0 minutes and 0 seconds.
I’ll reply with a different approach of the problem. My approach is to store the lengths in seconds. Then depending the needs, it’s easy to render these seconds as hh:mm:ss by using :
or to search on the length in a database:
SELECT * FROM videos WHERE length > 300; for example, to search for video with a length higher than 5 minutes.
If you really want to use a built-in function, perhaps for robustness, you can try
explode() is for pansies. This is a job for regular expressions!
Totally untested, but something like that ought to work. Note that this code assumes that the hour fragment will always be two digits (eg, a three-hour video would be 03:00:00 instead of 3:00:00 ).
EDIT: In retrospect, using regular expressions for this is probably a case of over-engineering; explode() will do the job just as well and probably even be faster in this case. But it was the first method to come to mind when I read the question.
Php seconds to hours and minutes
(PHP 4, PHP 5, PHP 7, PHP 8)
time — Возвращает текущую метку системного времени Unix
Описание
Возвращает количество секунд, прошедших с начала эпохи Unix (1 января 1970 00:00:00 GMT) до текущего времени.
Список параметров
У этой функции нет параметров.
Возвращаемые значения
Возвращает текущую метку системного времени.
Примеры
Пример #1 Пример использования time()
Результатом выполнения данного примера будет что-то подобное:
Примечания
Смотрите также
User Contributed Notes 21 notes
The documentation should have this info. The function time() returns always timestamp that is timezone independent (=UTC).
Two quick approaches to getting the time elapsed in human readable form.
$nowtime = time ();
$oldtime = 1335939007 ;
/** Output:
time_elapsed_A: 6d 15h 48m 19s
time_elapsed_B: 6 days 15 hours 48 minutes and 19 seconds ago.
**/
?>
A time difference function that outputs the time passed in facebook’s style: 1 day ago, or 4 months ago. I took andrew dot macrobert at gmail dot com function and tweaked it a bit. On a strict enviroment it was throwing errors, plus I needed it to calculate the difference in time between a past date and a future date.
Argument order (begin date, end date) doesn’t matter.
I needed to convert between Unix timestamps and Windows/AD timestamps, so I wrote a pair of simple functions for it.
Below, a function to create TNG-style stardates, taking 2009 to start stardate 41000.0. In fact, the offset is trivial to adjust if you wish to begin from a different date.
Here’s a snippet of code that demonstrates the difference:
// Find the next second
$nextSecond = time () + 1 ;
// TIME: 1525735820 uTIME: 1525735820.997716
// TIME: 1525735820 uTIME: 1525735820.998137
// TIME: 1525735820 uTIME: 1525735820.998528
// TIME: 1525735820 uTIME: 1525735820.998914
// TIME: 1525735820 uTIME: 1525735820.999287
// TIME: 1525735820 uTIME: 1525735820.999657
// TIME: 1525735820 uTIME: 1525735821.000026 time() is behind
// TIME: 1525735820 uTIME: 1525735821.000367 time() is behind
// TIME: 1525735820 uTIME: 1525735821.000705 time() is behind
// TIME: 1525735820 uTIME: 1525735821.001042 time() is behind
// TIME: 1525735820 uTIME: 1525735821.001379 time() is behind
// TIME: 1525735821 uTIME: 1525735821.001718
// TIME: 1525735821 uTIME: 1525735821.002070
// TIME: 1525735821 uTIME: 1525735821.002425
// TIME: 1525735821 uTIME: 1525735821.002770
// TIME: 1525735821 uTIME: 1525735821.003109
// TIME: 1525735821 uTIME: 1525735821.003448
// TIME: 1525735821 uTIME: 1525735821.003787
// TIME: 1525735821 uTIME: 1525735821.004125
// TIME: 1525735821 uTIME: 1525735821.004480
Here’s a little tweak for those having trouble with cookies being set in the future or past (even after setting the date.timezone directive in php.ini or using the function):
Does anyone know if the year 2038 issue will be solved in PHP?
Lets imagine it’s year 2039 and the time() function will return negative numbers? This is not acceptable.
Using the DateTime interface is nice, but will these timestamp helper functions be removed or fixed?
If you want to create a «rounded» time stamp, for example, to the nearest 15 minutes use this as a reference:
= 60 * 15 // 60 seconds per minute * 15 minutes equals 900 seconds
//$round_numerator = 60 * 60 or to the nearest hour
//$round_numerator = 60 * 60 * 24 or to the nearest day
//If it was 12:40 this would return the timestamp for 12:45;
//3:04, 3:00; etc.
?>
I built this function to get the strtotime numbers for the beginning and ending of the month and return them as arrays in an object. Cheers.
The issue are highlighting is with the date() function, not with time(). the following code demonstrates this:
A better way to get a nice time-format (1 year ago, 2 months until) without all the trailing months, days, hours, minutes, seconds in the result is by using the DateTime format and using the date_diff function as they both does most of the heavy lifting for you
Function below as example
// Ex. (time now = November 23 2017)
getTimeInterval ( «2016-05-04 12:00:00» ); // Returns: 1 year ago
getTimeInterval ( «2017-12-24 12:00:00» ); // Returns: 1 month until
I did an article on floating point time you can download from my website. Roun movements is the radial ounion movement and there is a quantum ounion movement as well, this code will generate the data for http://www.chronolabs.org.au/bin/roun-time-article.pdf which is an article on floating point time, I have created the calendar system as well for this time. It is compatible with other time and other solar systems with different revolutions of the planets as well as different quantumy stuff.
Here’s one way to generate all intermediate dates (in mySQL format) between any 2 dates.
Get start and end dates from user input, you’d need to do the basic validations that :
— start and end dates are valid dates
— start date //start date 2001-02-23
$sm = 2 ;
$sd = 23 ;
$sy = 2001 ;
//end date 2001-03-14
$em = 3 ;
$ed = 14 ;
$ey = 2001 ;
A method return GMT time (gmttime):
elapsed time function with precision:
Here is a version for the difference code that displays «ago» code.
It does use some precision after the time difference is longer than a day. ( ie days are more than 60 * 60 * 24 hours long )
// Make the entered date into Unix timestamp from MySQL datetime field
// Calculate the difference in seconds betweeen
// the two timestamps