PHP Programming 101

February 8th, 2008

Reading the current time: time() and microtime()

Posted by Conrad in Basic Programming, PHP


int time ( )
mixed microtime ( [bool get_as_float])

PHP has a basic function to get the current time in epoch format: time(). Time() takes no parameters, and returns the current timestamp representing the current time. As time() is the first function we have looked at, here is an example script:


print time();
$foo = time();
print $foo;
?>

As you can see, we can either print the return value of time() directly, or we can store it away in a variable then print the contents of the variable - the result is identical.

Working in Unix time means you are not tied down to any specific formatting - you do not need to worry about whether your date has months before days or vice versa, whether long months are used, whether day numbers of day words (Saturday, Tuesday, etc) are used, and so on.

Furthermore, to add one to a day (that is, to get the date of tomorrow), you can just add one day’s worth of seconds to your current timestamp: 60 x 60 x 24 = 86400. So, adding or subtracting 86400 to a date moves forward by one day, and so on - easy, really.

For more precise time values, you can use the microtime() function. When called without any parameters, this returns the current system time in seconds and microseconds, ordered microseconds first. For example: 0.82112000 1174676574

If you pass true to microtime() as its only parameter, PHP will return the time in a more obvious format - seconds.microseconds, like this: 1174676587.5996

When using microtime(), keep in mind that the return value is a floating-point number. There is a setting in your php.ini file called “precision”, which sets the number of significant digits to show in floating-point numbers - note that is significant digits, not decimal places, which means your return value from microtime() may not be as precise as you want. Above, for example, you can see we only have four decimal places returned - this is because php.ini defaults precision to 14, and there are ten digits before the decimal place.

If you increase the value of precision up to, say, 18, and run microtime() again, you will get results that are more accurate: 1174677004.8997819.

Source

Comments are closed.

Sorry, the comment form is closed at this time.

Bad Behavior has blocked 39 access attempts in the last 7 days.