Ben Packard
Ben Packard

Reputation: 26476

Creating time object from string using date_create_from_format

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?

Upvotes: 2

Views: 3086

Answers (2)

gen_Eric
gen_Eric

Reputation: 227230

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');

Upvotes: 4

hindmost
hindmost

Reputation: 7195

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.

Upvotes: 2

Related Questions