从数据库获取datetime字段

时间:2015-08-14 09:55:12

标签: mysql

我有一个罕见的问题。 我使用此查询来提取日期和时间

$datum_query = mysqli_query($kon, "SELECT EXTRACT(DAY FROM datetime) AS dan, EXTRACT(MONTH FROM datetime) AS mjesec,
    EXTRACT(YEAR FROM datetime) AS godina, EXTRACT(HOUR FROM datetime) AS sat, EXTRACT(MINUTE FROM datetime) AS minute, EXTRACT(SECOND FROM datetime) AS sekunde FROM cutoffs WHERE id=". $redCutoff["cutoff_id"] ."");
    $datum = mysqli_fetch_assoc($datum_query);

    if($datum["mjesec"] == 1){
        $datumLevering = $datum["dan"] . ". Jan " . $datum["godina"];
    }elseif($datum["mjesec"] == 2){
        $datumLevering = $datum["dan"] . ". Feb " . $datum["godina"];
    }elseif($datum["mjesec"] == 3){
        $datumLevering = $datum["dan"] . ". Ma " . $datum["godina"];
    }elseif($datum["mjesec"] == 4){
        $datumLevering = $datum["dan"] . ". Apr " . $datum["godina"];
    }elseif($datum["mjesec"] == 5){
        $datumLevering = $datum["dan"] . ". Mei " . $datum["godina"];
    }elseif($datum["mjesec"] == 6){
        $datumLevering = $datum["dan"] . ". Jun " . $datum["godina"];
    }elseif($datum["mjesec"] == 7){
        $datumLevering = $datum["dan"] . ". Jul " . $datum["godina"];
    }elseif($datum["mjesec"] == 8){
        $datumLevering = $datum["dan"] . ". Aug " . $datum["godina"];
    }elseif($datum["mjesec"] == 9){
        $datumLevering = $datum["dan"] . ". Sep " . $datum["godina"];
    }elseif($datum["mjesec"] == 10){
        $datumLevering = $datum["dan"] . ". Okt " . $datum["godina"];
    }elseif($datum["mjesec"] == 11){
        $datumLevering = $datum["dan"] . ". Nov " . $datum["godina"];
    }else{
        $datumLevering = $datum["dan"] . ". Dec " . $datum["godina"];
    }
    $leveringVrijeme = $datum["sat"] . "u" . $datum["minute"];
    $leveringDateandTime =  $datumLevering . "-" . $leveringVrijeme;

我在我的数据库中存储了一个日期时间字段,当我想获得结果时,如果该字段的值是例如2015-08-19 20: 10 :00 ,我在 $ leveringVrijeme (20u10)中获得了良好的结果,但如果该值是例如2015-08-19 20: 00 :00 ,然后我进入 $ leveringVrijeme (20u0)。

为什么我没有得到其他0?

2 个答案:

答案 0 :(得分:1)

您可以考虑使用VARCHAR

将其投射到字符串文字或CAST
SELECT EXTRACT(DAY FROM datetime) AS dan, 
EXTRACT(MONTH FROM datetime) AS mjesec,
    EXTRACT(YEAR FROM datetime) AS godina, 
    CAST(EXTRACT(HOUR FROM datetime) AS VARCHAR) AS sat, 
    CAST(EXTRACT(MINUTE FROM datetime) AS VARCHAR) AS minute, 
    CAST(EXTRACT(SECOND FROM datetime) AS VARCHAR) AS sekunde 
    FROM cutoffs 
    WHERE id=". $redCutoff["cutoff_id"] ."");

答案 1 :(得分:1)

extract将值作为数字返回。出于格式化的目的,您似乎需要零填充字符串。因此,请使用extract

,而不是date_format()
select date_format(datetime, '%d') as day,
       date_format(datetime, '%m') as mon,
       date_format(datetime, '%Y') as year,
       date_format(datetime, '%H') as hours,
       date_format(datetime, '%i') as minutes,
       date_format(datetime, '%s') as seconds

这将它们检索为零填充字符串。