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');
Related
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)) );
How do i convert this excel dataserial value 41225 back to date format 12-Nov-2012 using phpexcel and code igniter?
I have tried the following but it didn't work.
$G74 = $objPHPExcel->getActiveSheet()->getCell('B6')->getValue();
Dates in Excel are stored as number of days since 1st Jan 1900, except there is an off by one error due to 1900 not being a leap year. You can create therefore a DateTime object with this hack (valid for dates from 1st March 1900 onwards):
$n = 41225;
$dateTime = new DateTime("1899-12-30 + $n days");
You can format the DateTime Object with something like:
echo $dateTime->format("d M Y");
If you want to include the time as well as the date, multiply by 86400 (the number of seconds in a day) to get seconds since 1st Jan 1900 before you convert:
$n = 42898.35416666;
$dateTime = new DateTime("1899-12-30 + ". round($n * 86400) . " seconds");
Using the getFormattedValue() method rather than getValue() might help if the cell has a format mask that formats it as a date. getValue() returns a raw value, which (in this case) is the Excel serialized number.
Otherwise, the ExcelToPHP() or ExcelToPHPObject() methods in the PHPExcel_Shared_Date class should do the job of returning a unix timestamp or a PHP DateTime object that you can then format however you wish
I had to convert a dateserial number in decimal format ie: 42898.35416666 and the DateTime object does not take decimals.
Based on rjmunro's answer, and animuson's answer on how to convert decimals to hours and minutes, here is a solution for decimal Excel dates.
function dateSerialToDateTime($dateserial) {
$arrDate = explode(".", $dateserial);
$n = $arrDate[0];
$decimal = "." . $arrDate[1]; //decimal amount of seconds
$duration = 86400 * $decimal; //number of seconds in a day * decimal
$dateTime = new DateTime("1899-12-30 + $n days");
$converted = $dateTime->format("Y-m-d") . " " . gmdate("H:i:s", $duration);
return $converted;
}
$dateserial = 42898.35416666;
die(dateSerialToDateTime($dateserial));
//returns 2017-06-12 08:29:59
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...
I'm trying to display the time x started, the time x finished, and how long x took to complete. I have the start and end displaying correctly, but the following subtraction gives me a bonkers answer.
// to unix timestamps for subtraction
$startTime = strtotime($row['bp_rec_start']);
$endTime = strtotime($row['bp_rec_end']);
$timeTaken = $endTime - $startTime;
//back to date formats
$startTime = date('H:i',$startTime);
$endTime = date('H:i',$endTime);
$timeTaken = date('H:i',$timeTaken);
e.g. ( 01:24 - 01:23 = 07:01)
Thanks
Timestamps are seconds since 1970, each timestamp representing an absolute point in time. So $endTime - $startTime produces some point in time like 1975-04-12 07:01:52. Printing the hour and minute part of that will of course print 07:01. The timestamp itself though is the difference in seconds, so you can do:
echo "Difference: $timeTaken seconds";
You should of course look into DateInterval (look at the 3rd example).
How to get millisecond between two DateTime objects?
$date = new DateTime();
$date2 = new DateTime("1990-08-07 08:44");
I tried to follow the comment below, but I got an error.
$stime = new DateTime($startTime->format("d-m-Y H:i:s"));
$etime = new DateTime($endTime->format("d-m-Y H:i:s"));
$millisec = $etime->getTimestamp() - $stime->getTimestamp();`
I get the error
Call to undefined method DateTime::getTimestamp()
In the strict sense, you can't.
It's because the smallest unit of time for the DateTime class is a second.
If you need a measurement containing milliseconds then use microtime()
Edit:
On the other hand if you simply want to get the interval in milliseconds between two ISO-8601 datetimes then one possible solution would be
function millisecsBetween($dateOne, $dateTwo, $abs = true) {
$func = $abs ? 'abs' : 'intval';
return $func(strtotime($dateOne) - strtotime($dateTwo)) * 1000;
}
Beware that by default the above function returns absolute difference. If you want to know whether the first date is earlier or not then set the third argument to false.
// Outputs 60000
echo millisecsBetween("2010-10-26 20:30", "2010-10-26 20:31");
// Outputs -60000 indicating that the first argument is an earlier date
echo millisecsBetween("2010-10-26 20:30", "2010-10-26 20:31", false);
On systems where the size of time datatype is 32 bits, such as Windows7 or earlier, millisecsBetween is only good for dates between 1970-01-01 00:00:00 and 2038-01-19 03:14:07 (see Year 2038 problem).
Sorry to digg out an old question, but I've found a way to get the milliseconds timestamp out of a DateTime object:
function dateTimeToMilliseconds(\DateTime $dateTime)
{
$secs = $dateTime->getTimestamp(); // Gets the seconds
$millisecs = $secs*1000; // Converted to milliseconds
$millisecs += $dateTime->format("u")/1000; // Microseconds converted to seconds
return $millisecs;
}
It requires however that your DateTime object contains the microseconds (u in the format):
$date_str = "20:46:00.588";
$date = DateTime::createFromFormat("H:i:s.u", $date_str);
This is working only since PHP 5.2 hence the microseconds support to DateTime has been added then.
With this function, your code would become the following :
$date_str = "1990-08-07 20:46:00.588";
$date1 = DateTime::createFromFormat("Y-m-d H:i:s.u", $date_str);
$msNow = (int)microtime(true)*1000;
echo $msNow - dateTimeToMilliseconds($date1);
DateTime supports microseconds since 5.2.2. This is mentioned in the documentation for the date function, but bears repeating here. You can create a DateTime with fractional seconds and retrieve that value using the 'u' format string.
<?php
// Instantiate a DateTime with microseconds.
$d = new DateTime('2011-01-01T15:03:01.012345Z');
// Output the microseconds.
echo $d->format('u'); // 012345
// Output the date with microseconds.
echo $d->format('Y-m-d\TH:i:s.u'); // 2011-01-01T15:03:01.012345
// Unix Format
echo "<br>d2: ". $d->format('U.u');
function get_data_unix_ms($data){
$d = new DateTime($data);
$new_data = $d->format('U.u');
return $new_data;
}
function get_date_diff_ms($date1, $date2)
{
$d1 = new DateTime($date1);
$new_d1 = $d1->format('U.u');
$d2 = new DateTime($date2);
$new_d2 = $d2->format('U.u');
$diff = abs($new_d1 - $new_d2);
return $diff;
}
https://www.php.net/manual/en/class.datetime.php
Here's a function to do that + tests.
https://gist.github.com/vudaltsov/0bb623b9e2817d6ce359eb88cfbf229d
DateTime dates are only stored as whole seconds. If you still need the number of milliseconds between two DateTime dates, then you can use getTimestamp() to get each time in seconds (then get the difference and turn it into milliseconds):
$seconds_diff = $date2.getTimestamp() - $date.getTimestamp()
$milliseconds_diff = $seconds_diff * 1000