W3docs

localtime()

Sure thing! 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

Warning: localtime() was deprecated in PHP 7.0 and removed in PHP 8.0. This function is no longer available in modern PHP versions. For current projects, use DateTime or date() with date_default_timezone_set() to handle local time conversions safely.

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

Note: The returned local time depends on the server's configured timezone. Use date_default_timezone_set() to set it explicitly.

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

The syntax of PHP localtime()

<?php

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: Seconds (0-59).
  • 1: Minutes (0-59).
  • 2: Hours (0-23).
  • 3: Day of the month (1-31).
  • 4: Month (0-11, where 0 is January).
  • 5: Years since 1900.
  • 6: Day of the week (0-6, where 0 is Sunday).
  • 7: Day of the year (0-365).
  • 8: Whether Daylight Saving Time is in effect (1 if yes, 0 if no, -1 if unknown).

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


array(
  'tm_sec' => ...,
  'tm_min' => ...,
  'tm_hour' => ...,
  'tm_mday' => ...,
  'tm_mon' => ...,
  'tm_year' => ...,
  'tm_wday' => ...,
  'tm_yday' => ...,
  'tm_isdst' => ...
)

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

Example of PHP localtime() function

<?php

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

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

// 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

Practice

What is the function of localtime() in PHP?