2

I have a $timeString formatted as 8:00 PM ET. I am trying to create a date object using the following:

$time = date_create_from_format('g:i A e', $timeString);

(source: http://www.php.net/manual/en/datetime.createfromformat.php)

When I echo the result using date("H:i:s", $time) I am getting 7:00 PM ET. No matter which time I provide, I always receive 7pm (which is 0:00 GMT).

Am I using the format parameters incorrectly?

1
  • I don't think ET is a valid timezone identifier. Try EST. Commented Feb 5, 2014 at 19:02

2 Answers 2

4

There are a few problems here. One is that ET is not a valid timezone identifier. Try using EST (or EDT). See: http://www.php.net/manual/en/timezones.others.php

Second, date_create_from_format (or DateTime::createFromFormat) returns a DateTime object, so you cannot use it with the date() function.

Your code prints 00:00:00 because date_create_from_format failed, so it returned FALSE. date() expects the 2nd parameter to be an int, so it "converted" FALSE to 0. Because of that, you got 00:00:00.

You need to use the DateTime methods to work with a DateTime object. Like this:

$timeString = '8:00 PM EST';
$time = date_create_from_format('g:i A e', $timeString);

echo date_format($time, 'H:i:s');
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Actually, once I was using date_format correctly, ET seems to be handled as expected. As you point out, the documentation doesn't mention it. Any ideas why it is working?
@BenPackard: ET doesn't work for me, so no, no idea.
2

date_create_from_format() returns DateTime object. whereas date() expect 2nd parameter to be a timestamp (int). So you shouldn't use date(). Use DateTime::format() instead.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.