PHP add miliseconds as microtime to date - php

This is my code:
$d2 = new DateTime("2019-01-01 02:24:19.769002");
echo $d2->format("Y-m-d H:i:s.u");
$tBefore = microtime(true);
// GET ANOTHER DATA
$tAfter = microtime(true);
$d2->modify('+'.($tAfter-$tBefore).' microsecond');
echo $d2->format("Y-m-d H:i:s.u");
But my code return wrong date for milliseconds.
I want to add seconds with milliseconds to first date and get times of ANOTHER DATA.
Actually if ANOTHER DATA take 0.100 milliseconds, my result should be 2019-01-01 02:24:19.869002

You can use DateTime and DateInterval:
<?php
$d2 = new DateTime('2019-01-01 02:24:19.769002');
$tBefore = new DateTime();
// `sleep` to simulate work done between `$tBefore` and `$tAfter`
sleep(1);
$tAfter = new DateTime();
$d2->add($tBefore->diff($tAfter));
print_r($d2);
https://www.php.net/manual/en/class.dateinterval.php
https://www.php.net/manual/en/datetime.add
https://www.php.net/manual/en/datetime.diff

As of PHP 7.1, microseconds can also be easily added to DateTime using the modify method. The microsecond value must be an integer and cannot be a float. microtime (true) also delivers seconds as float and not microseconds.
$date = new DateTime("2019-01-01 02:24:19.769002");
$seconds = 0.100;
$intMicroseconds = intval($seconds * 1000000);
$date->modify($intMicroseconds.' microseconds');
echo $date->format("Y-m-d H:i:s.u");
//2019-01-01 02:24:19.869002

Related

Get the closest (in past) time based on a string

I want to create a function that can find the closest time, based in a string of second.
The system will receive an int number that equivalent of second of that time.
PHP must find the closest (in past) date.
Example:
//supose that an anterior script created it at "14-08-25 10:32:30"
//and now it's "14-08-25 10:33:12"
$seconds = 30; // the variable passed from an anterior script
$time_received= date('Y-m-d H:i:s'); // this is the time that I'll receive this
//so, from these 2 variables above, i must find "14-08-25 10:32:30"
Anyone have an idea how to do this?
I have just these variables:
The time right now, that is "14-08-25 10:33:12"
and the $seconds variable.
With these 2, I want to get "14-08-25 10:32:30"
It isn't completely clear to me what you are trying to accomplish, but I'm making a guess by using strtotime():
<?php
$seconds = 30;
$time = strtotime("-" . $seconds . " seconds");
echo date( "Y-m-d H:i:s", $time );
?>
Found.
I'm using this script:
$seconds = 30;
$new_date = new DateTime(date()); //the only two variables that i have
if($new_date->format('s')<$seconds){
$new_date->setTime($new_date->format('H'),$new_date->format('i')-1,$seconds);
$old_date = $new_date->format('Y/m/d H:i:s');
}else{
$new_date->setTime($new_date->format('H'),$new_date->format('i'),$seconds);
$old_date = $new_date->format('Y/m/d H:i:s');
}

Modify microseconds of a PHP DateTime object

I have a PHP DateTime object with microseconds created as follows:
$time = microtime(true);
$microseconds = sprintf('%06d', ($time - floor($time)) * 1000000);
$dt = new DateTime(date('Y-m-d H:i:s.' . $microseconds, $time));
How can I modify the microseconds value of $dt, without creating a completely new DateTime instance?
You can't.
There are three methods that can modify the value of a DateTime instance: add, sub and modify. We can rule out add and sub immediately because they work in terms of a DateInterval which does not have sub-second precision.
modify accepts a string in one of the standard recognized formats. Of those formats, only the relative ones are of interest here because the other ones work in an absolute manner; and there is no relative format that allows tweaking the msec part (that unit is not recognized).
as of PHP 7.1
DateTime::setTime() supports microseconds.
This seems to have been available since 7.1.0-rc4
$dt = new DateTime('2020-01-01 0:00');
$dt->modify('+500 ms'); // Milliseconds.
$dt->modify('+123456 usec'); // Microseconds.
$dt->modify('+123456 microseconds'); // This works too.
It's mentioned here in the manual.
Manually creating a DateTime object with micro seconds:
$d = new DateTime("15-07-2014 18:30:00.111111");
Getting a DateTime object of the current time with microseconds:
$d = date_format(new DateTime(),'d-m-Y H:i:s').substr((string)microtime(), 1, 8);
Difference between two DateTime objects in microseconds (e.g. returns: 2.218939)
//Returns the difference, in seconds, between two datetime objects including
//the microseconds:
function mdiff($date1, $date2){
$date1sec = strtotime($date1->format('d-m-Y H:i:s.u'));
$date2sec = strtotime($date2->format('d-m-Y H:i:s.u'));
//Absolute val of Date 1 in seconds from (EPOCH Time) - Date 2 in seconds from (EPOCH Time)
$secdiff = abs($date1sec-$date2sec);
//Creates variables for the microseconds of date1 and date2
$micro1 = $date1->format("u");
$micro2 = $date2->format("u");
if (($date1sec<$date2sec && $micro1>$micro2)||($date1sec>$date2sec && $micro1<$micro2)){
$microdiff = abs(1000000 - abs($micro1-$micro2));
$secdiff = $secdiff - 1;
} else {
$microdiff = abs($micro1 - $micro2);
}
//Creates the variable that will hold the seconds (?):
$difference = $secdiff.".".$microdiff;
return $difference;
}
Essentially it finds the difference for the DateTime Objects using strtotime and then adding the extra microseconds on.
Do you need me to create add and sub?
i had a similar problem and ended up having to wrap the whole thing
https://gist.github.com/chandeeland/9817516
For the people only in need to zero-out microseconds (I had to because of database layer) here's the snippet I ended up using:
$format = "Y-m-d H:i:s e";
$now = (new \DateTime())->format($format);
$dateTime = \DateTime::createFromFormat($format, $now);
Note that using $format = 'c', ISO 8601, will not work, as explained here (https://stackoverflow.com/a/10478469/8119317).

count hours remain between 2 dates with php

i have this dates
$dt_occ = mysql_result($info,0,"occ_data");
$dt_occ = strtotime($dt_occ);
$dt_occ = strtotime('+1 day' , $dt_occ);
$dt_unico = date('d/m/Y H:i',$dt_occ);
$dt_il = date('d/m/Y',$dt_occ);
$dt_alle = date('H:i',$dt_occ);
I need to know how many hours remain between now and $dt_unico
Take a look at the DateTime classes, they are much more flexible that strtotime() and date() (IMHO). Something like this will work for you:-
function getDiffInHours(\DateTime $earlierDate, \DateTime $laterDate)
{
$utc = new \DateTimeZone('UTC');
//Avoid side effects
$first = clone $earlierDate;
$second = clone $laterDate;
//First convert to UTC to avoid missing hours due to DST etc
$first->setTimezone($utc);
$second->setTimezone($utc);
$diff = $first->diff($second);
return 24 * $diff->days + $diff->h;
}
Use it like this for example:-
$hours = getDiffInHours(new \DateTime($dt_occ), (new \DateTime($dt_occ))->modify('+ 1 day'));
var_dump($hours); //24
I think this will work for you.
$dt1 = new DateTime($dt_occ);
$dt2 = new DateTime($dt_occ);
$dt2->modify("+1 day");
$interval = $dt2->diff($dt1);
echo $interval->hours;
If you're using PHP5.5 you can simply this a little bit:
$dt1 = new DateTimeImmutable($dt_occ);
$dt2 = $dt1->modify("+1 day");
$interval = $dt2->diff($dt1);
echo $interval->hours;
Since $dt_unico is derived from $dt_occ, which is a timestamp and time() gives the current time, also as a timestamp, subtracting the former from the latter will give the interval between them, in seconds.
Now, an hour is 60*60=3600 seconds, so:
$interval=(time()-$dt_occ)/3600;
Some notes, though:
I assumed that $dt_occ refers to the past. Future dates will give negative results, so if that's the case, switch the subtraction operands.
The above will give a floating point result. For an integral result, use the appropriate rounding function depending on the desired rounding method.

Doctrine2 subtract two datetimes

So in my database I got a datetime field, filled with e.g. 2012-09-19 11:20:33.
Now I'm trying to fetch the datetime.
$blabla = $something->getDatetime();
After that I create a new DateTime, which represents the time now
$now = new \DateTime("now");
And after that I want to subtract them like this (but it doesn't work)?
$test1 = strtotime($blabla);
$test2 = strtotime($now);
$diff = $test2 - $test1;
echo $diff;
My aim is to subtract the persisted datetime in the database from the time now...the result should be displayed in seconds...so 2012-09-19 11:22:22 - 2012-09-19 11:20:22 equals 120 (seconds).
I also tried to persist a unix timestamp into my database but unfortunately the field type timestamp doesn't exist.
If you want the answer displayed in seconds, then just subtract the timestamps:-
$blabla = $something->getDatetime();
$now = new DateTime();
$seconds = $now->getTimestamp() - $blabla->getTimestamp();
$blabla = $something->getDatetime();
$now = new \DateTime("now");
$diff = $now->diff($blabla);
Remember that $diff is a DateInterval object en you must use its methods and properties to get to the final desired result.

How to get millisecond between two dateTime obj?

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

Categories