I am currently converting a ASP.NET C# application to PHP. The service uses DateTime Ticks and I was wondering if there is an equivalent in PHP.
If not what is the best way for me to calculate a timespan?
Use microtime(true)
Please note the following, straight off the PHP manual
By default, microtime() returns a string in the form "msec sec", where sec is the current time measured in the number of seconds since the Unix epoch (0:00:00 January 1, 1970 GMT), and msec is the number of microseconds that have elapsed since sec expressed in seconds.
If get_as_float is set to TRUE, then microtime() returns a float, which represents the current time in seconds since the Unix epoch accurate to the nearest microsecond.
[Edit: I saw later that the DateTime ticks is also quite similar to PHP DateTime->diff method, so added it; realized I missed a parameter for microtime, thanks to freedompeace.]
I usually do it like this for benchmarking (kudo's also to freedompeace):
$time = microtime(true);
// do your thing
$diff = microtime(true) - $time;
See: http://php.net/microtime
For other dates, you can do it like this:
$date1 = new DateTime('05-04-2010');
$date2= new DateTime('yesterday');
// returns a DateInterval object
$diff = $date1->diff($date2);
The DateInterval object has a topology like this:
public integer $DateInterval->y ; public integer $m ; public integer $d ; public integer $h ; public integer $i ; public integer $s ; public integer $invert ; public mixed $days ;
DateTime Class http://www.php.net/manual/en/class.datetime.php
Diff method http://www.php.net/manual/en/datetime.diff.php
DateInterval Object http://www.php.net/manual/en/class.dateinterval.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With