-1

My PHP command which is below that I used to outcome the current date and time is one hour behind the current time. How can I make use PHP to output the actual current UK time and date?

Command in PHP

new DateTime(); 

Output which the current time is one hour behind the current time.

[Date the login occurred] => DateTime Object
        (
            [date] => 2019-04-10 12:54:54.000000
            [timezone_type] => 3
            [timezone] => UTC
        )

4 Answers4

8

You need to set your default timezone to get the "correct" value. The time you are getting is correct, but is in UTC, not daylight savings time as the UK is currently using:

date_default_timezone_set('UTC');
echo (new DateTime())->format('Y-m-d H:i:s') . PHP_EOL;
date_default_timezone_set('Europe/London');
echo (new DateTime())->format('Y-m-d H:i:s');

Output:

2019-04-10 13:03:33 
2019-04-10 14:03:33

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95
  • 1
    @darren substar - Keep in mind that when your application runs in different countries, it is better to stick with UTC, and do the conversion only when showing the date/time in the user interface. This way one can evade a lot of problems with time leaps, and date/time values from different timezones. – martinstoeckli Apr 10 '19 at 16:06
4

It's because you didn't pass the time zone, so it takes servers' default one. In your case, UTC is the default. Even though UK is at GMT 0 offset, it uses daylight savings time which UTC doesn't use.

What you're after is:

$dt = new DateTime("now", new DateTimeZone('Europe/London'));
Mjh
  • 2,904
  • 1
  • 17
  • 16
1

The answers above are correct. But if you want to apply the setting across your entire application (i.e. if you are using DateTime in more than one .php file), you may want to edit your php.ini file, and search for date.timezone in your php.ini, then modify it to use London time zone.

date.timezone='Europe/London'
Temi Fakunle
  • 672
  • 6
  • 7
0

I would recommend to set the timezone in the php.ini file.

Typically the php.ini is in you /etc/php/{your_php_version}/php.ini

There should be a entry that looks like that:

[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
;date.timezone =

You can set the timezone like:

date.timezone = "US/Central"

https://www.php.net/manual/en/timezones.europe.php

The_Dome
  • 70
  • 6
  • You're suggesting that the user affects entire PHP by altering initialization configuration, instead of programmatically setting the time zone as fit. Why? You're making the suggestion but you're not explaining the reason why it's good / better / useful. – Mjh Apr 10 '19 at 13:26