Monday, September 10, 2018

How do I convert to/from 24-hour time and AM/PM time in PHP?

In databases, times and datetimes may be stored as "13:30:00" or "1984-05-01 15:45:59".

But you may want to convert this to something that displays with AM/PM, or maybe you want to collect a time that is AM/PM and store it according to your DB schema.

You can display 24-hour time in AM/PM with...

print date('G:ia', strtotime("13:30:00"));

And a 24-hour datetime with in AM/PM with...

print date('Y-m-d G:ia', strtotime("1984-05-11 13:30:00"));

If you wanted to go in the opposite direction, and display an AM/PM time with 24-hour time...

print date('H:i:s', strtotime("1:30 AM"));

And if you want to display AM/PM datetime in 24-hour datetime format...

print date('Y-m-d H:i:s', strtotime("1:30 AM"));

No comments:

Post a Comment