Current Location: Home> Latest Articles> Detailed Guide on PHP Timestamp Conversion to Local Time

Detailed Guide on PHP Timestamp Conversion to Local Time

gitbox 2025-07-15

Detailed Guide on PHP Timestamp Conversion to Local Time

In PHP, a timestamp is an integer that represents the number of seconds from 00:00:00 GMT on January 1, 1970, to a specific point in time. PHP provides several built-in functions to convert between timestamps and human-readable date/time formats. This article will demonstrate how to convert a timestamp into local time and explain the relevant PHP functions.

Common PHP Timestamp Functions

PHP provides some very useful functions to help developers work with timestamps. Below are a few commonly used timestamp-related functions:

time() Function

The time() function returns the current Unix timestamp, which is the number of seconds from the Unix epoch (January 1, 1970, 00:00:00 GMT) to the current time.

Example code:


print time(); // Outputs the current timestamp

strtotime() Function

The strtotime() function parses a date/time string into a Unix timestamp. It can handle various formats, such as:

  • “now” for the current date and time.
  • Relative times like “+5 days”, “-1 month”, etc.
  • Specific date/time strings like “10 September 2000”.

Example code:


print strtotime('now'); // Outputs the current timestamp
print strtotime('10 September 2000'); // Outputs the timestamp for a specific date

date() Function

The date() function formats a timestamp into a human-readable string based on a given format. The format can be predefined constants or a custom string.

Example code:


print date('Y-m-d H:i:s', time()); // Outputs the current date and time in a readable format

Converting Timestamp to Local Time

To convert a Unix timestamp to local time in PHP, you can use the date() function in combination with setting the correct timezone.

First, set the local timezone using the date_default_timezone_set() function:


date_default_timezone_set('Asia/Shanghai');

Next, use the date() function to convert the Unix timestamp to local time:


$timestamp = 1631589818;
$date = date('Y-m-d H:i:s', $timestamp);
echo $date; // Outputs the local time

The code above will output: 2021-09-14 09:10:18.

Conclusion

This article introduced some common PHP functions related to timestamps, such as time(), strtotime(), and date(). Using these functions, developers can easily convert timestamps to local time or format local time into a timestamp. Understanding and applying these functions in development is essential for handling time and dates effectively.