正确格式化javascript日期到MySQL

时间:2013-10-10 19:25:46

标签: javascript php mysql codeigniter

我正在创建一个基于JavaScript的日历,使用full-calendar.js作为主要骨干。 所以在其他方面将新的event插入MySQL数据库,我有以下代码片段:

$.post("http://localhost/calendar/index.php/calendar/insert_event", 
      { 
        title  : title,
        start  : start,
        end    : end,
        allDay : allDay,
        url    : ''
      }, 
      function(answer) {
        console.log(answer);
      }
); 

startend日期只是Date()个对象:

var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();

calendar.php控制器中,我得到以下输出:

{"title":"lunch",
 "start":"Tue Oct 08 2013 08:00:00 GMT-0700 (Pacific Standard Time)",
 "end":"Tue Oct 08 2013 08:30:00 GMT-0700 (Pacific Standard Time)",
 "allDay":"false",
 "url":""}

startendDATETIME MySQL表中的类型,其中列具有相同的类型。 当我使用insert Active Record函数执行CodeIgniter's时,它会向表中插入而不会出现其他问题。但是,当我查看MySQL数据库以查看输出时,我看到:

mysql> select * from calendar_utility;
+----+-----+-------+---------------------+---------------------+--------+
| id | url | title | start               | end                 | allday |
+----+-----+-------+---------------------+---------------------+--------+
|  1 |     | lunch | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 |      0 |
+----+-----+-------+---------------------+---------------------+--------+
1 row in set (0.00 sec)

如何正确格式化JavaScript Date()以正确插入MySQL数据库?

1 个答案:

答案 0 :(得分:4)

我可能会将JS Date对象转换为符合MySQL DATETIME格式的字符串,如下所示:

$.post("http://localhost/calendar/index.php/calendar/insert_event", 
      { 
        title  : title,
        start  : start.getFullYear() + "-" + (start.getMonth()+1) + "-" + start.getDate() + " " + start.getHours() + ":" + start.getMinutes() + ":" + start.getSeconds(),
        end    : end.getFullYear() + "-" (end.getMonth()+1) + "-" + end.getDate() + " " + end.getHours() + ":" + end.getMinutes() + ":" + end.getSeconds(),
        allDay : allDay,
        url    : ''
      }, 
      function(answer) {
        console.log(answer);
      }
);