W3docs

Get current date, given a timezone in PHP?

To get the current date and time in a specific timezone in PHP, you can use the date_default_timezone_set function to set the timezone and then use the date function to get the current date and time.

To get the current date and time in a specific timezone in PHP, you can use the date_default_timezone_set function to set the timezone and then use the date function to get the current date and time.

Here's an example of how to do this:

Example of getting current date, given a timezone in PHP

<?php

// Set the timezone to "Asia/Tokyo"
date_default_timezone_set('Asia/Tokyo');

// Get the current date and time in the specified timezone
$currentDateTime = date('Y-m-d H:i:s');

echo $currentDateTime;

This will output the current date and time in the "Asia/Tokyo" timezone in the format YYYY-MM-DD HH:MM:SS. You can adjust the format of the date and time by changing the format string passed to the date function.

Note: date_default_timezone_set() modifies the timezone for the entire script environment, which can cause side effects in larger applications. PHP automatically validates timezone identifiers and will emit a warning if an invalid ID is provided. For better maintainability, modern PHP recommends using DateTime and DateTimeZone objects, which handle timezones locally without affecting global state.

Modern approach using DateTime and DateTimeZone

<?php
$timezone = new DateTimeZone('Asia/Tokyo');
$currentDateTime = new DateTime('now', $timezone);
echo $currentDateTime->format('Y-m-d H:i:s');