Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Get unix timestamp from string without setting default timezone in PHP
In PHP, you can get a Unix timestamp from a string without setting a default timezone by specifying the timezone directly in the string or using DateTime objects. This allows you to work with different timezones without affecting your application's global timezone setting.
Getting Default Timezone
First, let's check what the default timezone is set to ?
<?php echo date_default_timezone_get(); ?>
UTC
Using strtotime() with Timezone in String
You can include the timezone directly in the date string when using strtotime() ?
<?php
$timestamp = strtotime("1/1/2020 00:00:00 America/Los_Angeles");
echo "Timestamp: " . $timestamp . "<br>";
echo "Date: " . date("Y-m-d H:i:s", $timestamp);
?>
Timestamp: 1577862000 Date: 2020-01-01 08:00:00
Using DateTime Object with Timezone
The DateTime class provides more precise control over timezone handling ?
<?php
$date = new DateTime("2020-01-01 00:00:00", new DateTimeZone("America/Los_Angeles"));
$timestamp = $date->getTimestamp();
echo "Timestamp: " . $timestamp . "<br>";
echo "UTC Date: " . gmdate("Y-m-d H:i:s", $timestamp);
?>
Timestamp: 1577862000 UTC Date: 2020-01-01 08:00:00
Without Timezone Specification
When no timezone is specified, the string is interpreted using the default timezone ?
<?php
$timestamp = strtotime("1/1/2020 00:00:00");
echo "Timestamp: " . $timestamp . "<br>";
echo "Date: " . date("Y-m-d H:i:s", $timestamp);
?>
Timestamp: 1577836800 Date: 2020-01-01 00:00:00
Comparison
| Method | Timezone Control | Flexibility |
|---|---|---|
| strtotime() with timezone | Limited | Medium |
| DateTime object | Full control | High |
| Without timezone | Uses default | Low |
Conclusion
Use DateTime objects for precise timezone control when converting strings to timestamps. This approach avoids the need to modify your application's default timezone setting while ensuring accurate time conversions.
