Convert from MySQL datetime to another format with PHP

后端 未结 18 1212
醉话见心
醉话见心 2020-11-22 01:08

I have a datetime column in MySQL.

How can I convert it to the display as mm/dd/yy H:M (AM/PM) using PHP?

18条回答
  •  醉酒成梦
    2020-11-22 01:16

    The approach I suggest works like the following. First, you create a basic datetime object from a mysql-formatted string; and then you format it the way you like. Luckily, mysql datetime is ISO8601-compliant, so the code itself could look quite simple and elegant. Keep in mind though that datetime column doesn't have a timezone information, so you need to convert it appropriately.

    Here's the code:

    (new ISO8601Formatted(
        new FromISO8601('2038-01-19 11:14:07'),
        'm/d/Y h:iA'
    ))
        ->value();
    

    It outputs 01/19/2038 11:14AM -- hopefully what you expect.

    This example uses meringue library. You can check out some more of it if you fancy.

提交回复
热议问题