Unix timestamps (also known as Epoch time) are widely used in web development for logging, database operations, and time-sensitive calculations. This guide explains multiple methods to generate Unix timestamps in PHP, along with best practices and advanced techniques.
1. Basic Methods to Get Unix Timestamp
a. Using time()
Function
The simplest way to 获取当前 Unix 时间戳 is via the built-in time()
function:
$timestamp = time(); // Returns current timestamp as an integer echo $timestamp; // Example output: 1711500000
Key Notes:
- Returns the number of seconds since
1970-01-01 00:00:00 UTC
. - Fast and lightweight for basic use cases.
b. Using strtotime()
Function
Convert a human-readable date string to a timestamp:
$dateString = "2025-12-31 23:59:59"; $timestamp = strtotime($dateString); echo $timestamp; // Output: 1746095999
Supported Formats:
- Natural language inputs:
"next Thursday"
,"+2 days"
. - ISO 8601:
"2025-03-27T15:30:00+08:00"
. - Relative dates:
"now"
,"yesterday"
.
c. Using DateTime
Class
For object-oriented and timezone-aware operations:
$date = new DateTime(); $timestamp = $date->getTimestamp(); echo $timestamp; // Current timestamp
Example with Custom Dates:
$date = new DateTime("2025-03-27 00:00:00"); $timestamp = $date->getTimestamp(); echo $timestamp; // Output: 1711500000
2. Handling Timezones
PHP uses the server’s default timezone by default. To ensure consistency:
1. Set a Global Timezone in php.ini
:
date.timezone = "Asia/Shanghai"
2. Use DateTime
with Timezone Explicitly:
$date = new DateTime("now", new DateTimeZone("America/New_York")); $timestamp = $date->getTimestamp();
3. Advanced Techniques
a. Microsecond Precision
To include microseconds (useful for high-precision logging):
$microtime = microtime(true); // Returns a float (e.g., 1711500000.123456) $timestamp = (int) $microtime; // Convert to integer for standard Unix timestamp
b. Parsing Invalid Dates
Handle edge cases where strtotime()
returns false
:
$dateString = "invalid-date"; $timestamp = strtotime($dateString); if ($timestamp === false) { throw new Exception("Invalid date format"); }
c. Converting Between Timestamps and Dates
Timestamp to Human-Readable Date:
$timestamp = 1711500000; $date = date("Y-m-d H:i:s", $timestamp); // Output: "2025-03-27 00:00:00"
Date String to Timestamp:
$dateString = "2025-03-27"; $timestamp = strtotime($dateString); // Output: 1711500000
4. Common Use Cases
Database Operations:
Store timestamps in INT(11)
or BIGINT(20)
columns for efficient queries.
Token Expiration:
Generate time-limited tokens:
$expiresAt = time() + 3600; // Token expires in 1 hour
Caching:
Use timestamps to invalidate cached data:
$cacheKey = "user_data_123_{$timestamp}";
5. Best Practices
- Avoid Hardcoding Timezones: Use
DateTimeZone
objects for consistency. - Validate Inputs: Sanitize date strings before parsing to prevent errors.
- Use UTC Internally: Store timestamps in UTC and convert to local time for display.
- Performance: Prefer
time()
overDateTime
for high-frequency operations.
Summary Table
Method | Use Case | Example Code |
---|---|---|
time() | Current timestamp | $timestamp = time(); |
strtotime() | Convert date string to timestamp | $timestamp = strtotime("2025-12-31"); |
DateTime Class | Timezone-aware operations | $date = new DateTime(); |
microtime(true) | Microsecond precision | $micro = microtime(true); |
By mastering these methods, you can efficiently work with Unix timestamps in PHP for both simple and complex applications. Always test edge cases (e.g., leap seconds, historical dates) to ensure robustness.