douchi0028 2016-09-25 22:25
浏览 114
已采纳

使用laravel未将日期保存到mySQL数据库

I've got a jquery datepicker

$(function() {
    var date = new Date();
    var currentMonth = date.getMonth();
    var currentDate = date.getDate();
    var currentYear = date.getFullYear();
    $('.datepicker').datepicker({
    showOn: 'focus',changeMonth: true,
    minDate: new Date(currentYear, currentMonth, currentDate),
    changeYear: true,

});
});

with some validation

    $this->validate($request, [
        "date" => 'required|date',
    ]);

and some conversion for the date to pass through to the database

    $date = $request->input('date');
    $date2 = DateTime::createFromFormat('m/d/Y',$date);
    $date3 = $date2->format("Y-d-m");

If I dd($date3) at this point, with a chosen date, I get something like this

"2016-29-09"

All well and good, mysql appears to save in a y-d-m format.

Now when I go to pass it through

    Message::where('id', $messageId)->update([
        'updated_at' => Carbon\Carbon::now(),
        'subject' => 'Status: Price quote delivered.',  
        'quoted' => 1,
        'price' => $request->input('price'),
        'estimated_date'  => $date3,            
    ]);

everything gets passed to the database except the date. The date just stays at 0000-00-00 in the database.

Help?

展开全部

  • 写回答

4条回答 默认 最新

  • dq804806 2016-09-25 22:35
    关注

    Note that you are saving date as YEAR-DAY-MONTH and the correct format for DATE is YEAR-MONTH-DAY.

    Also note that value of $date3 is "2016-29-09", this will insert value in your table as "0000-00-00" due to invalid value of Month and correct range of Month is (1-12) for data type DATE.

    Solution:

    You need to change the date format (YEAR-MONTH-DAY) as per your Data type of column.

    $date3 = $date2->format("Y-m-d"); // something like 2016-09-26
    

    You can also follow the reference: http://dev.mysql.com/doc/refman/5.7/en/datetime.html

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部