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:
<?php 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. The only exceptions to this are when clocks move as a result of summer time and when they move as a result of leap seconds being added, but there are easy ways to work around these.
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.
If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!
Next chapter: Converting from a string >>
Previous chapter: Working with Date and Time
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.