【问题标题】:correctly formatting javascript date to MySQL [duplicate]将javascript日期正确格式化为MySQL [重复]
【发布时间】:2013-10-18 17:31:56
【问题描述】:

我正在创建一个基于 JavaScript 的日历,使用 full-calendar.js 作为主干。 因此,在其他将新的event 插入 MySQL 数据库中时,我有以下代码 sn-p:

$.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":""}

startend 是 MySQL 表中的 DATETIME 类型,其中列具有上述相同类型。 当我使用CodeIgniter's 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 数据库中正确插入?

【问题讨论】:

标签: javascript php mysql codeigniter


【解决方案1】:

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

【讨论】:

  • 并不是说-(start.getMonth()+1) 之间缺少+ 连接符会导致错误。 Stackoverflow 不允许我进行少于 6 个字符的“编辑”。
  • 谢谢,我已经更正了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-07
  • 1970-01-01
  • 2013-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多