0
0
PhpHow-ToBeginner · 3 min read

How to Use time() Function in PHP: Syntax and Examples

In PHP, you use the time() function to get the current Unix timestamp, which is the number of seconds since January 1, 1970. Simply call time() without any arguments to get this integer value representing the current time.
📐

Syntax

The time() function has a simple syntax with no parameters. It returns an integer representing the current Unix timestamp.

  • Return value: Integer timestamp (seconds since 1970-01-01 00:00:00 UTC)
php
int time ( void )
💻

Example

This example shows how to use time() to get the current timestamp and display it. It also converts the timestamp to a readable date format using date().

php
<?php
// Get current Unix timestamp
$currentTimestamp = time();

// Display the timestamp
echo "Current timestamp: " . $currentTimestamp . "\n";

// Convert timestamp to readable date
echo "Current date and time: " . date('Y-m-d H:i:s', $currentTimestamp) . "\n";
?>
Output
Current timestamp: 1718995200 Current date and time: 2024-06-22 00:00:00
⚠️

Common Pitfalls

Some common mistakes when using time() include:

  • Expecting time() to return a formatted date string instead of an integer timestamp.
  • Passing arguments to time(), which it does not accept.
  • Confusing time() with other date/time functions like date() or strtotime().

Always remember to convert the timestamp to a readable format if needed.

php
<?php
// Wrong: passing argument to time()
// $wrong = time('now'); // This will cause a warning

// Right: call time() without arguments
$correct = time();

// Convert to readable date
echo date('Y-m-d H:i:s', $correct);
?>
Output
2024-06-22 00:00:00
📊

Quick Reference

FunctionDescriptionReturn Type
time()Returns current Unix timestampint
date(format, timestamp)Formats a timestamp into a readable date stringstring
strtotime(time_string)Converts a date/time string to a timestampint|false

Key Takeaways

Use time() without arguments to get the current Unix timestamp as an integer.
The timestamp counts seconds since January 1, 1970 (UTC).
Convert timestamps to readable dates using date().
Do not pass arguments to time() as it accepts none.
Remember time() returns an integer, not a formatted date string.