How extract years, months, days, hours, minutes, seconds from a mysql date?

前端 未结 6 938
一向
一向 2020-12-15 07:06

In my mysql database I have dates like this: 2011-01-06 09:39:114525

and I need to extraxt separately years, months, days, hours, minutes, seconds from it.

S

6条回答
  •  时光取名叫无心
    2020-12-15 07:18

    I would like to suggest one more cleaner way. And this can be achieved without on any library or framework.

    First, you should convert the datetime string to a timestamp (strtotime works on almost every format). Then using getdate as follows :

    $dateAsTimestamp = strtotime("2011-01-06 09:39:11.45");
    $dateTime = getdate($dateAsTimestamp);
    

    The function returns all components of date and time as an associative array.

    Array
    (
        [seconds] => 11
        [minutes] => 39
        [hours] => 9
        [mday] => 6
        [wday] => 4
        [mon] => 1
        [year] => 2011
        [yday] => 5
        [weekday] => Thursday
        [month] => January
        [0] => 1294306751
    )
    

    Now can be accessed as per your requirement

    echo($dateTime['hours']);
    echo($dateTime['minutes']);
    echo($dateTime['seconds']);
    
    $MONTH = $dateTime['month'];
    

    More on Date/Time Functions - getdate and strtotime

提交回复
热议问题