Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Equivalent of C# ticks

Tags:

date

c#

php

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?

like image 453
GaryDevenay Avatar asked Feb 24 '23 12:02

GaryDevenay


2 Answers

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.

like image 189
foxy Avatar answered Feb 26 '23 03:02

foxy


[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

like image 35
Arend Avatar answered Feb 26 '23 03:02

Arend