1

我正在创建一个基于 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);
      }
); 

start日期end只是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":""}

start并且endDATETIMEMySQL 表中的类型,其中列具有与上面相同的类型。当我insert使用CodeIgniter'sActive Record 函数时,它会插入到表中而没有进一步的问题。但是,当我查看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 db 中正确插入?

4

1 回答 1

5

我可能会将 JSDate对象转换为符合 MySQLDATETIME格式的字符串,如下所示:

$.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);
      }
); 
于 2013-10-10T19:39:26.053 回答