Reputation: 3107
As you may know it's highly recommended by WordPress to theme/plugin authors to don't change the WordPress timezone by PHP functions like date_default_timezone_set.
I addition to that you may receive wrong date and time values when you use php date function because of not setting default timezone by PHP.
I mean you may receive 10 for date('G')
while the exact hour is 15 in the selected timezone in WordPress->Settings->General->Timezone option.
So what should you do if you need the correct date and time values in selected timezone for WordPress website?
Upvotes: 7
Views: 30111
Reputation: 3107
You can use current_datetime function. It returns a DateTimeImmutable
object with the timezone selected in WordPress general options. Then you can use format
or other methods of the object to get your desired date and time.
$current_datetime = current_datetime()->format('Y-m-d H:i:s');
You should use current_time function of WordPress instead of PHP date function for getting local date and time in WordPress. It will return correct value for you based on selected timezone in WordPress general options.
For me current_time('G')
returns exactly 15 while PHP date('G')
returns 10 which is not correct.
Hope it helps somebody since I didn't find related thread in the stackoverflow.
Upvotes: 16
Reputation: 771
Since WordPress 5.3, you can use current_datetime
to get it correctly:
$current_date_time = current_datetime()->format('Y-m-d H:i:s');
The result will respect the time zone defined in the Settings → General → Time Zone
select field, in the WordPress dashboard.
See also the available formatting options.
Note: please don't use current_time
, it's not recommended anymore.
Upvotes: 1
Reputation: 55
You should use current_time function of WordPress instead of PHP date function for getting local date and time in WordPress. It will return correct value for you based on selected timezone in WordPress general options.
$Date_Time = current_datetime()
Retrieves the current time based on specified type.
current_time( string $type, int|bool $gmt )
Retrieves the current time based on specified type.
Source :
File: wp-includes/functions.php
function current_time( $type, $gmt = 0 ) {
// Don't use non-GMT timestamp, unless you know the difference and really need to.
if ( 'timestamp' === $type || 'U' === $type ) {
return $gmt ? time() : time() + (int) ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
}
if ( 'mysql' === $type ) {
$type = 'Y-m-d H:i:s';
}
Upvotes: -1
Reputation: 136
You can also install a plugin like Shortcode for Current Date to display the current time in your respective time zone. It also provides a great overview of various date and time formats.
Upvotes: 0