← Back to Chapters

PHP time()

⏱ PHP time()

? Quick Overview

The time() function in PHP returns the current Unix timestamp, which is the number of seconds since January 1, 1970, 00:00:00 GMT. It is widely used for time calculations, comparisons, and date handling.

? Key Concepts

  • Returns current Unix timestamp in seconds
  • Timezone independent value
  • Commonly combined with date()
  • Useful for calculations and comparisons

⚙️ Syntax / Theory

? View Code Example
// Returns the current Unix timestamp
time();

? Example 1: Using time()

This example shows how to retrieve the current Unix timestamp.

? View Code Example
// Display the current Unix timestamp
<?php
echo time();
?>

? Explanation

The time() function outputs the total number of seconds elapsed since the Unix epoch.

? Example 2: Time Calculations

Using timestamps for future or past date calculations.

? View Code Example
// Calculate time for one day later
<?php
$time_now = time();
$one_day_later = $time_now + 86400;
echo "Current time: " . date("Y-m-d H:i:s", $time_now) . "<br>";
echo "One day later: " . date("Y-m-d H:i:s", $one_day_later);
?>

? Explanation

By adding seconds to the timestamp, we can easily calculate future or past dates and format them using date().

? Use Cases

  • Session expiration handling
  • Countdown timers
  • Logging events with timestamps
  • Comparing dates

✅ Tips & Best Practices

  • Always use seconds when working with timestamps
  • Format timestamps before displaying to users
  • Store timestamps in databases for flexibility

? Try It Yourself

  • Display the timestamp for one week later
  • Calculate seconds remaining today
  • Check if a timestamp is past or future