localtime() is a built-in PHP function that converts a Unix timestamp into an array of local time values. This array contains information such as the year, month, day, hour, minute, and second of the local time.

Here's the basic syntax of the localtime() function:


localtime(timestamp, is_associative)

The timestamp parameter is the Unix timestamp you want to convert, and is_associative is an optional Boolean parameter that determines whether the returned array should be associative or not.

If is_associative is false or not specified, the array will be indexed numerically. The array will contain the following values in order:

  • 0: The number of years since 1900.
  • 1: The number of months since January (0-11).
  • 2: The day of the month (1-31).
  • 3: The number of seconds since midnight (0-59).
  • 4: The number of minutes past the hour (0-59).
  • 5: The number of hours past midnight (0-23).
  • 6: The day of the week (0-6, where 0 is Sunday).
  • 7: The number of days since January 1 (0-365).

If is_associative is set to true, the array keys will be named after the values above, like so:

  'tm_year' => ...,
  'tm_mon' => ...,
  'tm_mday' => ...,
  'tm_sec' => ...,
  'tm_min' => ...,
  'tm_hour' => ...,
  'tm_wday' => ...,
  'tm_yday' => ...

Here are some examples of using the localtime() function:


// Get the current local time
$now = time();
$localtime = localtime($now);

// Get the local time for a specific Unix timestamp
$timestamp = 1646563200; // March 5, 2022, 12:00:00 AM UTC
$localtime = localtime($timestamp);

// Get the local time as an associative array
$now = time();
$localtime = localtime($now, true);
echo "The current year is " . ($localtime['tm_year'] + 1900);

These examples show how you can use localtime() to convert Unix timestamps into local time values and manipulate them as needed in your PHP code.

Practice Your Knowledge

What is the function of localtime() in PHP?

Quiz Time: Test Your Skills!

Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.

Do you find this helpful?