浏览器和数据库之间的日期格式不一致

时间:2017-01-10 09:14:30

标签: php date

我的表单上的一个字段是日期,而使用谷歌浏览器时,它会在单击该字段时提供一个日历框。如果我选择日期格式为DD-MM-YYYY但是当它添加到我的表格时它显示为YYYY-MM-DD。

我猜我错过了我的代码并在插入时将其设置为默认格式? 这是我的插入代码:

if (isset($_POST['addloan'])):

$username=$_POST['username'];

$user_query="SELECT * from loanusers where username = '$username'"; //think about how you are storing usernames in db, in this query you have to enter the username exactly how it is stored    
$userresult= mysqli_query($connection, $user_query);

$row = mysqli_fetch_array($userresult, MYSQLI_ASSOC);

$emailaddress = $row['emailaddress'];

$product=$_POST['product'];
$product_desc=$_POST['product_desc'];
$serial=$_POST['serial'];
$date_collected=$_POST['date_collected'];
$date_return=$_POST['date_return'];
$returned=$_POST['returned'];

if (isset($_FILES['loanform'])){
    $exten = pathinfo($_FILES['loanform']['name'], PATHINFO_EXTENSION);
    $loanform = $_FILES['loanform']['name'];
    $uploadfile = "loanforms/$loanform";

    if (strtolower($exten) == 'pdf'){
        move_uploaded_file($_FILES['loanform']['tmp_name'] , $uploadfile);
        $my_query="INSERT INTO loans VALUES ('','$username','$emailaddress','$product','$product_desc','$serial','$date_collected','$date_return','$loanform','$returned','')";
        $result= mysqli_query($connection, $my_query);
    } else{
        header('Location: incorrectext.php');
    }
}


    if ($result):
            header ('location: homepage.php?confirm=New loan successfully created');
        else :
            echo "<b>This didn`t work, error: </b>";
            echo mysqli_error($connection);
endif;

ENDIF;

1 个答案:

答案 0 :(得分:0)

您的数据库表很可能设置为以YYYY-MM-DD格式存储日期。您可以做的最好的事情是在提交表单之前和之后重新格式化日期。

// $date holds your submitted date in DD-MM-YYYY
$date = $_POST['date'];

// Reformat date
$oDate = DateTime::createFromFormat('d-m-Y', $date);

// In your query
$stmt = 'insert into table (somevalue, someother, date) VALUES ('bla', 'blabla', '".$oDate->format('Y-m-d')."')';

检索日期时可以做同样的事情:

<?php
$date = '2016-12-10';
$oDate = DateTime::createFromFormat('Y-m-d', $date);
?>

<input type="date" value="<?= $oDate->format('d-m-Y'); ?>" />

更新

浏览器在呈现日期输入方面不受限制。例如,Chrome会在日期选择器中使用用户的本地日期格式。在你的后端,这可能会导致一些问题。

这就是为什么我建议您将date更改为text输入并使用jQuery添加日期选择器。这样可以防止提交日期不一致,并使您可以更好地控制提交的格式。

相关问题