duanpang1987 2013-10-10 19:25
浏览 42

正确格式化javascript日期到MySQL [重复]

This question already has an answer here:

I'm creating a JavaScript based calendar, using full-calendar.js as main backbone. So in other to insert a new event into a MySQL database, I have the following code snippet:

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

the start and end dates are simply Date() objects:

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

in the calendar.php controller, I get the following output:

{"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 and end are DATETIME Types in a MySQL table where the columns have the same type was above. When I do the insert using CodeIgniter's Active Record functions, it inserts to the table without further problems. However, when I look at the MySQL database to see the output, I see:

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)

How can I correct format the JavaScript Date() to insert correctly at the MySQL db?

</div>
  • 写回答

1条回答 默认 最新

  • doushishi6513 2013-10-10 19:39
    关注

    I would probably convert the JS Date objects to strings conforming to the MySQL DATETIME format like this:

    $.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);
          }
    ); 
    
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料