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.

357 views

Edited: 2021-03-07 17:16

The time function is used to return the current time in seconds since the unix epoch, this is also known as unix time; the unix epoch is defined as January 1 1970 00:00:00 GMT.

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.

See: Current unix timestamp

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:

  1. How much faster is C++ than PHP to increment and display a counter in a loop?
  2. How to create a router in PHP that also handles request- methods and parameters.
  3. Detecting the request method used to fetch a web page with PHP, routing, HTTP responses, and more.
  4. How to create a custom error handler for PHP that handles non-fetal errors.
  5. Setting custom HTTP Headers with cURL is useful when changing User Agent or Cookies. Headers can be changed two ways, both using the curl_setopt function.

More in: PHP Tutorials