javascript - 将 javascript 日期正确格式化为 MySQL

标签 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);
      }
); 

开始结束 日期只是Date() 对象:

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

calendar.php Controller 中,我得到以下输出:

{"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":""}

startend 是 MySQL 表中的 DATETIME 类型,其中的列具有与上面相同的类型。 当我使用 CodeIgniter 的 Active Record 函数执行 insert 时,它会插入到表中而不会出现其他问题。但是,当我查看 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 数据库?

最佳答案

我可能会将 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);
      }
); 

关于javascript - 将 javascript 日期正确格式化为 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19304531/

相关文章:

php - 使用 where in 条件和最新时间​​戳连接两个 MySQL 查询

php - 我的 nginx 与 spawncgi php 一起运行,POST 和 GET 数据无法通过

mysql - MongoDB 或 MySQL 数据库

php - 在 sql 调用之前显示 Bootstrap 警报

javascript - 关于 JavaScript 变量

javascript - Rails : After input, 显示差异

javascript - 使用 Vue JS 定位 v-repeat 中的最后一项

PHP: DateTime::__construct() 错误

php - "Push"循环中关联数组末尾的对象

javascript - Jasmine 测试在迭代 div 中的多个结果时以不合逻辑的顺序运行代码?