php round time, keep string format - php

I'm rounding time to one minute using:
$mytime = mdate("H:i:s", $time_in_seconds);
$rounded_time = date('H:i:s', round(strtotime($mytime)/60)*60);
The output is for example: 01:09:00 from not rounded 01:08:34.
How can use the code but keep the seconds format rather than change to date?

what about using
$rounded_time = date('H:i:0');
?

Related

UTC time with 7 decimals calculation

I need to calculate the difference between 2 UTC time values with 7 decimals in PHP 7.3
Can I simply do the following:
val1 = 20200205120415.6513380; //first timestamp
val2 = 20200205120415.6535670; //second timestamp
$diff = $val2 - $val1; //should be difference between the 2 timestamps
The value of the above calculation is 0.002229. If I am doing it correctly is that value in seconds or microseconds and will I be able to convert it into a UNIX epoch timestamp?
I strongly suspect that the above times are not simple numbers; they BCD (binary coded decimal) for 2020-02-05-12:04:15.6513380. You can't do simple math on these, and you'll need to parse them to convert to a unix timestamp.
Depending on your language, it may be easiest to parse these by turning them into strings and taking the first four characters as the year, the next two as the month, etc.
Here is my current solution for completeness.
The values on the right of the . is indeed fractional seconds. So in PHP to get the difference I did the following:
$start = 20200205120415.6513380;
$end = 20200205120415.6535670;
//get value left of . and then create datetime object to later convert to seconds
list($datetime, $usecStart) = explode(".", $start);
$startTime = date_create_from_format("YmdHis", $datetime);
list($datetime, $usecEnd) = explode(".", $end);
$endTime = date_create_from_format("YmdHis", $datetime);
//get timestamp in seconds and add franction or microseconds back
$start = $startTime->getTimestamp().".".$usecStart;
$end = $endTime->getTimestamp().".".$usecEnd;
//get difference in seconds and fraction or microseconds
echo $end - $start;
Here is another way using datetime->diff() function:
$start = new DateTime('2020-02-05T12:04:15.6513380Z');
$end = new DateTime('2020-02-05T12:04:15.6535670Z');
$diff = $start->diff($end);
echo $diff->format('%h:%i:%s.%F');

PHP - Difference between two times

I've created a timing system for a charity race. I'm trying to find the difference between the start time and the finishers time using PHP. I'm not sure I'm recording the times correctly, but this is the start time i just recorded...
20180808180653
And this is a finisher time...
20180808180654
The difference between them is roughly 1 hour 24, but when i use...
date('h:i:s', $finshTime-$startTime)
I get 03:24:20 not 01:34:20.
Can someone please help?
The date method accepts as "integer Unix timestamp". You are supplying instead a number of seconds (1 in your example).
$start = '20180808180653';
$end = '20180808180654';
$diff = $end - $start;
var_dump($diff); //1
$d = date('h:i:s', $$diff);
var_dump($d); //04:00:01
//the above is wrong. You need to try something like the code below
$dStart = new DateTime($start);
$dEnd = new DateTime($end);
$interval = $dStart->diff($dEnd);
var_dump($interval->format('%h:%i:%s'));
I'd be leery using a string representation of a datetime that looks like that. Convert the whole thing into a date format that makes sense like yyyy-mm-dd hh:mm:ss, or a valid unix time stamp.
Your first approach isn't that far off, you just need to use a strtotime function. I'd guarantee that you can first make an accurate Date or Unix time representation of those strings you are using. Rest should fall into place.
First check if the type of $finshTime and $startTime are integer.
you can use get variable type:
gettype($startTime);
if this is the case try this with ():
$diff_date = date('h:i:s', ($finshTime - $startTime) );
if $startTime and $finshTime are string try this:
$diff_date = date('h:i:s', (strtotime($finshTime) - strtotime($startTime)) );

Get date+time timestamp

I need a timestamp code similar to this JavaScript code:
new Date().getTime()
I tried this PHP code:
$date = new DateTime();
$ts = $date->getTimestamp();
which returns 1376399143 but the JavaScript code returns 1376399143263, I think my PHP code generates a timestamp for only the date. How can I get the timestamp for the time portion as well?
use the code below
$time = mktime(date("H"),date("i"),date("s"),date("n"),date("j"),date("Y"));
echo $time;
for details information on mktime , check this link
You could use microtime, but if you do not need the additional precision (which will get lost because of networking), just divide the javascript time by 1000.
You should use microtime
$seconds = microtime(true); // false = int, true = float
echo round(($seconds * 1000));
The php code generates the timestamp for date and time, but it returns the number of seconds from 1-1-1970. Javascript returns the value in miliseconds.
You could use microtime(true)*1000; for a similar result that Javascript.

Getting a time difference in mongoDB?

I'm using PHP + mongoDB.
How can I get a time difference between two time values?
I have a real time value which is string
$realtime = "2010-01-01 12:00:00";
and another value which is unixstamp time,
$mongotime = new Mongodate(strtotime($realtime));
So I can use either a string time value or unix time stamp.
But I'm not sure the way to get time difference between two values.
Should I just subtract two $mongotime values and does it give me a time difference in seconds?
If you have 2 unix timestamps...
$date = $item['pubdate'];
(etc ...)
$unix_now = time();
$result = strtotime($date, $unix_now);
$unix_diff_min = (($unix_now - $result) / 60);
$min = round($unix_diff_min);
This will give number of mins between the 2 timestamps...

Determining elapsed time

I have two times in PHP and I would like to determine the elapsed hours and minutes. For instance:
8:30 to 10:00 would be 1:30
A solution might be to use strtotime to convert your dates/times to timestamps :
$first_str = '8:30';
$first_ts = strtotime($first_str);
$second_str = '10:00';
$second_ts = strtotime($second_str);
And, then, do the difference :
$difference_seconds = abs($second_ts - $first_ts);
And get the result in minutes or hours :
$difference_minutes = $difference_seconds / 60;
$difference_hours = $difference_minutes / 60;
var_dump($difference_minutes, $difference_hours);
You'll get :
int 90
float 1.5
What you now have to find out is how to display that ;-)
(edit after thinking a bit more)
A possibility to display the difference might be using the date function ; something like this should do :
date_default_timezone_set('UTC');
$date = date('H:i', $difference_seconds);
var_dump($date);
And I'm getting :
string '01:30' (length=5)
Note that, on my system, I had to use date_default_timezone_set to set the timezone to UTC -- else, I was getting "02:30", instead of "01:30" -- probably because I'm in France, and FR is the locale of my system...
You can use the answer to this question to convert your times to integer values, then do the subtraction. From there you'll want to convert that result to units-hours-minutes, but that shouldn't be too hard.
Use php timestamp for the job :
echo date("H:i:s", ($end_timestamp - $start_timestamp));
$d1=date_create()->setTime(8, 30);
$d2=date_create()->setTime(10, 00);
echo $d1->diff($d2)->format("%H:%i:%s");
The above uses the new(ish) DateTime and DateInterval classes. The major advantages of these classes are that dates outside the Unix epoch are no longer a problem and daylight savings time, leap years and various other time oddities are handled.
$time1='08:30';
$time2='10:00';
list($h1,$m1) = explode(':', $time1);
list($h2,$m2) = explode(':', $time2);
$time_diff = abs(($h1*60+$m1)-($h2*60+$m2));
$time_diff = floor($time_diff/60).':'.floor($time_diff%60);
echo $time_diff;

Categories