3
$t = DateTime::createFromFormat('Gi', '900');
$time_str = $t->format('gi a');
echo $time_str; //outputs 600 pm instead of 9am. Why? and How do I get 9am?

I am not sure where I am going wrong.. I am following what is given here in terms of date formatting: http://php.net/manual/en/function.date.php

Thanks!

1
  • 2
    no idea why but this works > DateTime::createFromFormat('G i', '9 00'); i guess its because the time must be separated in some way Commented Feb 10, 2012 at 16:33

2 Answers 2

2

The documentation you linked is for the date() function. The DateTime::createFromFormat is not the same (though the format strings are pretty much identical).

I expect the format parsing is having trouble recognizing the difference between the hour and minute components.

If you split them up with a space, you get the desired result:

$t = DateTime::createFromFormat('G i', '9 00');
$time_str = $t->format('gi a');
echo $time_str;
// Output is 900 am

Edit:

The inability for PHP to parse a format string like Gi is a known bug. The parser for G doesn't know whether to read 9 or 90 and in the latter case that 90 is too high.

Sign up to request clarification or add additional context in comments.

4 Comments

Ah thanks! that helps! Thing is, for quick computation of time (and because I need to use them as array indices), I am storing them as numbers [0 to 2359]. So the best way to convert them to am/pm for printing would be to split them to hour and min, subtract 12 etc?
If you pad the time string with a leading zero, it seems to parse that correctly. 0900 = 900 am However I would strongly consider putting a colon between the hours and minutes components of the output time when using am/pm, as it is standard formatting.
Yes, that is true. But 01000 fails. It was simpler to just do it manually :)
Well you wouldn't pad a 4-digit time; only when the hour component is 1 digit. Padding generally implies adding characters so that output is a fixed-width across expected values. Example: str_pad($time, 4, "0", STR_PAD_LEFT);
2

As i said in my comment this works :

$t = DateTime::createFromFormat('G i', '9 00');
$time_str = $t->format('gi a');
echo $time_str.PHP_EOL;

Cannot find any where written down - but suspect the time needs to be separated ... either by space or colon or something else

2 Comments

That makes perfect sense. Good answer! ;)
Thanks! I accepted the other answer because of the link to the bug :)

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.