0
votes

Regardless, of what timezone I feed in, I get same result.

I expected time fed into (2nd argument) to be UTC - it does not seem to be.

In such case, what is the use of third argument - timezone, if we do not get time in selected timezone, but repetition of time we fed into?

I see offset (in parentheses), but fail to understand, how is that practically useful.

I appreciate, if someone would explain, what I do not get here right.

When I use:

DateTime::createFromFormat("Y-m-d H:i:s", "2019-05-31 10:00:56", new DateTimeZone('America/Fortaleza'));

I get this:

DateTime @1559307656 {#1978
  date: 2019-05-31 10:00:56.0 America/Fortaleza (-03:00),
}

I expected to get:

DateTime @1559307656 {#1978
  date: 2019-05-31 07:00:56.0 America/Fortaleza (-03:00),
}

Actually, I do not get any change, regardless of timezone fed in:


>>> DateTime::createFromFormat("Y-m-d H:i:s", "2019-05-31 10:00:56", new DateTimeZone('UTC'))
DateTime @1559296856 {#1979
  date: 2019-05-31 10:00:56.0 UTC (+00:00),
}

>>> DateTime::createFromFormat("Y-m-d H:i:s", "2019-05-31 10:00:56", new DateTimeZone('Europe/Moscow'))
DateTime @1559286056 {#1958
  date: 2019-05-31 10:00:56.0 Europe/Moscow (+03:00),
}
1
Why would you expect to see any of those values? Which actual timezone is that original value from?John Conde
Lets say: Europe/WarsawJeffz

1 Answers

1
votes

You're misunderstanding the use of the third parameter. It is used to tell DateTime::createFromFormat what the timezone of the time you have passed in is, which also becomes the timezone of the result. If your input time is UTC, that is the appropriate value for the third parameter, and you can then use DateTime::setTimeZone to set the timezone of the value:

$date = DateTime::createFromFormat("Y-m-d H:i:s", "2019-05-31 10:00:56", new DateTimeZone('UTC'));
$date->setTimeZone(new DateTimeZone('America/Fortaleza'));
var_dump($date);

Output:

object(DateTime)#2 (3) {
  ["date"]=> string(26) "2019-05-31 07:00:56.000000"
  ["timezone_type"]=> int(3)
  ["timezone"]=> string(17) "America/Fortaleza" 
}

Demo on 3v4l.org