Time function in PHP
The time() function may be used to get the current time in seconds that has passed since the unix epoch, defined as January 1 1970 00:00:00 GMT.
Created: 2023-08-26 00:00
echo time(); // Outputs E.g: 1695890472
PHP's time function creates a numeric timestamp in the unix format. This is also known as unix time, or the number of seconds passed since the unix epoch – that is, 00:00:00 UTC on 1 January 1970.
Right now there has approximately passed:
x
seconds since the unix epoch, and the current date in a readable Y-m-d H:i:s format is:
x.
The format of the date can be adjusted as needed, there are also different options that you can use depending your preferred date/time formatting.
You can show a human readable version of the number returned by time by combining it with the date function:
$tomorrow = time() + 86400; // 86.400 is equal to ~1 day in seconds
echo 'Tomorrow: '. date('Y-m-d H:i:s', $tomorrow) ."\n";
Example output:
Tomorrow: 2021-02-15 12:01:11
To get the current date, simply call the date function directly:
date_default_timezone_set("UTC");
echo date('Y-m-d H:i:s'); // 2021-02-14 12:01:11
The time function always returns a timestamp that is independent of time zone (UTC), so remember to define the time zone using date_default_timezone_set when using the date function.
The time function returns an integer and does not accept any parameters.
Time table
The following table shows how many seconds there is over different time spans:
1 day | 86400 |
1 weak | 604800 |
1 month | 2629746 |
1 year | 31556952 |
Note that these values are not precise due to leap seconds, and also because some months have 30 days while others only have 26 days. If precision is important, you should instead use the date function.
Tell us what you think: