PHP TimeZone functions are used to manipulate and set the time zone for date and time operations. They ensure accurate date-time handling across different geographical regions.
date_default_timezone_set() – Sets the default timezone for the script.date_default_timezone_get() – Returns the current default timezone.DateTimeZone – Represents a timezone.timezone_offset_get() – Retrieves offset from UTC in seconds.PHP uses the server’s default timezone unless explicitly changed. For predictable results, always set a timezone before working with dates.
// Set and retrieve the default timezone
<?php
date_default_timezone_set("America/New_York");
echo "Current timezone: " . date_default_timezone_get();
echo "<br>";
echo "Current time: " . date("Y-m-d H:i:s");
?>
The script sets the timezone to America/New_York and displays the current date and time according to that region.
// Calculate timezone offset from UTC
<?php
$timezone = new DateTimeZone("America/New_York");
$datetime = new DateTime("now", $timezone);
echo "Time zone offset: " . $timezone->getOffset($datetime) . " seconds";
?>
DateTime and DateTimeZone for advanced operations.DateTime objects with different timezones and calculate the difference.