CodeBlanks Logo Icon CodeBlanks

Timestamps with time()

PHP course · Intermediate · Lesson 106/115

Learn to get and use the Unix timestamp with time().

time() and the Unix timestamp

In PHP the time() function returns the current time as a Unix timestamp. This value is the number of seconds since 1 January 1970 00:00:00 UTC and it is an integer.

For example, $now = time(); assigns a large integer like 1700000000 to $now. Pass this number as the second argument to date() to print the matching date.

Timestamps are the backbone of date math; because they are in seconds, adding and subtracting is easy.

Timestamp arithmetic

Because timestamps are in seconds, date arithmetic is easy. One day is 60 * 60 * 24 = 86400 seconds; one hour is 3600, one minute is 60 seconds.

To get tomorrow's timestamp you write $tomorrow = time() + 86400;. For one week later use time() + 7 * 86400.

Print the result with date('Y-m-d', $tomorrow) in a readable form. This is handy for short calculations; for complex work the DateTime class is safer.

Exercise Compute the date one week later

From the given $now = 1700000000 timestamp compute one week (7 days) later: $nextWeek = $now + 7 * 24 * 60 * 60;. Then print it with date('Y-m-d', $nextWeek).

Show example solution
Compute $nextWeek = $now + 7 * 24 * 60 * 60; then write echo date('Y-m-d', $nextWeek);
Example solution:
<?php
date_default_timezone_set('UTC');
$now = 1700000000;

$nextWeek = $now + 7 * 24 * 60 * 60;
echo date('Y-m-d', $nextWeek);

Test yourself

  1. What does the time() function return?

    • Seconds since 1 January 1970 (an integer)
    • Today's date as a 'Y-m-d' string
    • A microsecond-precision float
    • A timezone name (e.g. UTC)
    Show answer

    Seconds since 1 January 1970 (an integer) — Correct. time() returns the Unix timestamp (an integer in seconds).

  2. Compute seconds in one day

    $day_in_seconds = 60 * 60 * ____;
    Show answer
    $day_in_seconds = 60 * 60 * 24;
  3. Match time units

    60 seconds
    1 minute
    3600 seconds
    1 hour
    86400 seconds
    1 day
    time()
    Current timestamp

All lessons in Intermediate