tags:

views:

124

answers:

2

How can i convert times like 2 pm or 3 am to HH:MM:SS format in php?

Thats all what my question is.

Regards Zeeshan

+7  A: 

Like this:

$date = '2pm';
echo date('H:i:s', strtotime($date));

Result:

14:00:00

And:

$date = '2am';
echo date('H:i:s', strtotime($date));

Result:

02:00:00

More Info:

Update:

To convert it back:

$date = '14:00:00';
echo date('HA', strtotime($date));

Result:

14PM
Sarfraz
Sorry, this doesn't consider DST transitions. You should prefix `date_default_timezone_set("UTC");`
Artefacto
Can you also tell me how to covert it back? i mean from 14:00:00 to 2pm
Zeeshan Rang
@Zeeshan Rang: See my updated answer please.
Sarfraz
A: 

(this should be a comment, but it's too long)

The reason Sarfraz's solution is incomplete is because it doesn't account for DST transaitions. During DST transitions, some hours may not exist.

Consider the timezone is Europe/Lisbon and we're in March 28th 2010, when DST kicked in.

When we hit 1am, we change from UTC+0 to UTC+1, i.e., we skip 1 hour. Example:

date_default_timezone_set("Europe/Lisbon");
$date = '2010-03-28 1am';
$date2 = '2010-03-28 1:30am';
echo date('H:i:s', strtotime($date)),"\n";
echo date('H:i:s', strtotime($date2)),"\n";

gives

02:00:00
02:30:00

Therefore, Sarfraz solution will fail unless when you say you want to convert 1am to 01:00, these times always refer to the current day in the server's timezone.

Artefacto
@Artefacto: Sure good point, updated into the answer.
Sarfraz
@Sarfraz I think you didn't understand my comment. Changing to UTC has the advantage there are no timezone transitions, therefore "1am" is always converted to "01:00". Of course, this may or may not be the behavior the OP wants, he didn't say if "1am" refers to "1am today" or "1am generally". In the first case, changing the timezone to the relevant one is the the solution, otherwise he should change it to UTC.
Artefacto
@Artefacto: Ok then only OP knows what he needs but your comment is useful here :)
Sarfraz