php css vector image

How to Use PHP time() Function with Example Code

The time() function in PHP returns the current time as a Unix timestamp—the number of seconds that have passed since January 1, 1970, 00:00:00 GMT (known as the Unix Epoch). It is commonly used when working with dates, logs, and session handling.

Syntax

int time()

This function does not require any parameters and returns the current timestamp as an integer.

Basic Example

<?php
echo time();
// Output: 1714655000 (example)
?>

This prints the current number of seconds since the Unix Epoch.

Formatting the Timestamp

You can combine time() with date() to convert the timestamp into a readable date and time:

<?php
echo date("Y-m-d H:i:s", time());
// Output: 2025-05-02 14:45:00
?>

Use Cases

  • Store creation or update times in a database
  • Calculate elapsed time for tasks
  • Build countdown timers or expiration logic
  • Track user activity or log events

Measuring Execution Time

Here's an example to calculate how long a process takes:

<?php
$start = time();
sleep(3); // simulate delay
$end = time();

echo "Execution time: " . ($end - $start) . " seconds";
?>

Conclusion

The time() function is a simple and powerful tool in PHP. Whether you are logging events, timing scripts, or handling date logic, mastering this function is essential for every PHP developer.