-2

How can I determine, in php, whether a certain date and time (ex: 2018-09-30 09:00:00) use winter-time or summer-time? And once I know whether it is one or the other, how do I add 1 hour to the dates in summer-time?

Example:

2018-08-10 08:00:00 --> this is summer-time, so I need to add 1hour --> 2018-08-10 09:00:00

2018-08-10 23:30:00 --> adding 1 hour will be 2018-08-11 00:30:00 (in this case the day changes)

2018-12-12 08:00:00 --> this is winter-time, the date stay the same.

Michael
  • 324
  • 2
  • 20
  • If all you have is a string like "2018-08-10 08:00:00", then there simply is no timezone information there. You can get the timezone currently being used by your PHP environment, but it is unclear if that is what you are asking. Now, perhaps you could make some big assumptions and say that any date between X and Y is "summer time". That would be pretty easy to do if you create a DateTime object from your string. – Patrick Q Oct 17 '18 at 13:21

1 Answers1

2

There's an I format character in date formatting PHP, which returns 1 if it's a daylight saving time (summer time).

$d1 = date('I', strtotime('2018-08-10 08:00:00'));
$d2 = date('I', strtotime('2018-08-10 23:30:00'));
$d3 = date('I', strtotime('2018-12-12 08:00:00'));

echo 'D1 is ' . ($d1?'summer':'winer') . 'time' . PHP_EOL;
echo 'D2 is ' . ($d2?'summer':'winer') . 'time' . PHP_EOL;
echo 'D3 is ' . ($d3?'summer':'winer') . 'time' . PHP_EOL;

Output:

D1 is summertime
D2 is summertime
D3 is winertime

Working code: https://3v4l.org/DVjdn

Then you can use Datetime::add() method to add an hour when you need it.

Jakub Matczak
  • 15,341
  • 5
  • 46
  • 64
  • Not a criticism, but I assume this uses U.S. daylight savings time, right? I believe the UK switches time a couple weeks before or after. Not sure where the OP is, but it could be something to keep in mind. Nice answer though, wasn't aware of that format option :) – Patrick Q Oct 17 '18 at 13:38
  • it is actually not that the post author wanted. your time depends on the server timezone settings. and the daylight savings time is calculated, depending on the server settings, but not on the given datetime string. – Sergej Oct 17 '18 at 13:51
  • @PatrickQ it depends on server's timezone setting. Why would it depend on U.S. time? Is U.S. some kind of special place in the world? ;-) – Jakub Matczak Oct 18 '18 at 07:06
  • @Sergej, Of course it depends on server's timezone. OPs datetime string doesn't contain timezone information, so there's no such thing as *settings of given datetime string*. – Jakub Matczak Oct 18 '18 at 07:07
  • @JakubMatczak I was asking, not stating. – Patrick Q Oct 18 '18 at 17:30