【问题标题】:Convert JavaScript to date object to MySQL date format (YYYY-MM-DD)将 javascript 到日期对象转换为 mysql 日期格式 (YYYY-MM-DD)
【发布时间】:2011-01-17 19:35:38
【问题描述】:

我正在尝试使用 javascript 将日期对象转换为有效的 mysql 日期 - 最好的方法是什么?

【问题讨论】:

标签: javascript mysql date


【解决方案1】:

最好使用像 Date.js(尽管已经多年未维护)或 Moment.js 这样的库。

但要手动执行,您可以使用Date#getFullYear()Date#getMonth()(它以 0 = 一月开始,因此您可能需要 + 1)和 Date#getDate()(一个月中的某天)。只需将月份和日期填充为两个字符,例如:

(function() {
    Date.prototype.toYMD = Date_toYMD;
    function Date_toYMD() {
        var year, month, day;
        year = String(this.getFullYear());
        month = String(this.getMonth() + 1);
        if (month.length == 1) {
            month = "0" + month;
        }
        day = String(this.getDate());
        if (day.length == 1) {
            day = "0" + day;
        }
        return year + "-" + month + "-" + day;
    }
})();

用法:

var dt = new Date();
var str = dt.toYMD();

请注意,该函数有一个名称,这对于调试目的很有用,但由于是匿名作用域函数,因此不会污染全局命名空间。

使用当地时间;对于 UTC,只需使用 UTC 版本(getUTCFullYear 等)。

警告:我只是把它扔掉了,它完全未经测试。

【讨论】:

    【解决方案2】:

    看看这个方便的库,满足您的所有日期格式化需求:http://blog.stevenlevithan.com/archives/date-time-format

    【讨论】:

      【解决方案3】:

      在第一个示例中有点错别字,当一天的长度小于 1 时,它会将月份而不是日期添加到结果中。

      如果你改变了,效果很好:

          if (day.length == 1) {
              day = "0" + month;
          }
      

          if (day.length == 1) {
              day = "0" + day;
          }
      

      感谢您发布该脚本。

      修正后的函数如下:

      Date.prototype.toYMD = Date_toYMD;
      function Date_toYMD() {
          var year, month, day;
          year = String(this.getFullYear());
          month = String(this.getMonth() + 1);
          if (month.length == 1) {
              month = "0" + month;
          }
          day = String(this.getDate());
          if (day.length == 1) {
              day = "0" + day;
          }
          return year + "-" + month + "-" + day;
      }
      

      【讨论】:

        【解决方案4】:

        可以!

        function Date_toYMD(d)
        {
            var year, month, day;
            year = String(d.getFullYear());
            month = String(d.getMonth() + 1);
            if (month.length == 1) {
                month = "0" + month;
            }
            day = String(d.getDate());
            if (day.length == 1) {
                day = "0" + day;
            }
            return year + "-" + month + "-" + day;
        }
        

        【讨论】:

          【解决方案5】:
          function js2Sql(cDate) {
              return cDate.getFullYear()
                     + '-'
                     + ("0" + (cDate.getMonth()+1)).slice(-2)
                     + '-'
                     + ("0" + cDate.getDate()).slice(-2);
          }
          

          【讨论】:

            【解决方案6】:
            // function
            getDate = function(dateObj){
                var day = dateObj.getDay() < 9 ? '0'+dateObj.getDay():dateObj.getDay();
                var month = dateObj.getMonth() < 9 ? '0'+dateObj.getMonth():dateObj.getMonth();
                return dateObj.getFullYear()+'-'+month+'-'+day;
            }
            
            // example usage
            console.log(getDate(new Date()));
            
            // with custom date
            console.log(getDate(new Date(2012,dateObj.getMonth()-30,dateObj.getDay()));
            

            【讨论】:

              【解决方案7】:

              这对我有用,只需编辑字符串:

              var myDate = new Date();
              var myDate_string = myDate.toISOString();
              var myDate_string = myDate_string.replace("T"," ");
              var myDate_string = myDate_string.substring(0, myDate_string.length - 5);
              

              【讨论】:

              • 这里有很多问题。不要重新声明var。阅读有关“吊装”的信息。此外,这就足够了,new Date().toISOString().slice(0, 10)
              • @Gajus 对我来说 Date().toISOString().slice(0, 10) 不够失败,有几个日期 - 例如 1979 年 6 月 7 日错误 1 ​​天
              • -1 当您使用 toISOString() 时,您将日期从显示的时区转换为 UTC 时间。例如,如果您正在查看的网页是 GMT-6 并显示 GMT-6 时间,并且您的浏览器在 GMT-5 的计算机上运行,​​那么当您使用 toISOString() 时,您现在将拥有 UTC 时间离开网页 5 小时而不是 6 小时
              【解决方案8】:

              获取日期

              new Date().toJSON().slice(0, 10)
              //2015-07-23
              

              日期时间

              new Date().toJSON().slice(0, 19).replace('T', ' ')
              //2015-07-23 11:26:00
              

              请注意,生成的日期/日期时间将始终采用 UTC 时区

              【讨论】:

              • OP 需要 MySQL DATE 对象,而不是 DATETIME,因此您需要“/T.*/”而不是“'T'”。除此之外,想知道为什么这不是最受好评的答案?
              • 为什么不是这个? (new Date()).toISOString().substring(0, 10)
              • 请注意,这在 9999 年之后将无法使用;)
              • 当我这样做时 (new Date(str_date)).toISOString().substring(0, 10) 日期变成了 str_date 的前一天。从字符串解析到日期时不准确
              • @KubaHoluj 我会确保在 cmets 中添加一个注释,以便可怜的草皮在 10000 年审查我的代码
              【解决方案9】:

              https://stackoverflow.com/a/11453710/3777994的最短版本:

              /**
               * MySQL date
               * @param {Date} [date] Optional date object
               * @returns {string}
               */
              function mysqlDate(date){
                  date = date || new Date();
                  return date.toISOString().split('T')[0];
              }
              

              使用:

              var date = mysqlDate(); //'2014-12-05'
              

              【讨论】:

                【解决方案10】:

                就这个:

                Object.defineProperties( Date.prototype ,{
                    date:{
                         get:function(){return this.toISOString().split('T')[0];}
                    },
                    time:{
                         get:function(){return this.toTimeString().match(/\d{2}:\d{2}:\d{2}/)[0];}
                    },
                    datetime:{
                         get : function(){return this.date+" "+this.time}
                    }
                });
                

                现在你可以使用

                sql_query = "...." + (new Date).datetime + "....";
                

                【讨论】:

                  【解决方案11】:

                  我需要这个作为文件名和当前时区的时间。

                  const timezoneOffset = (new Date()).getTimezoneOffset() * 60000;
                  
                  const date = (new Date(Date.now() - timezoneOffset))
                      .toISOString()
                      .substring(0, 19)
                      .replace('T', '')       // replace T with a space
                      .replace(/ /g, "_")     // replace spaces with an underscore
                      .replace(/\:/g, ".");   // replace colons with a dot
                  

                  来源

                  【讨论】:

                    【解决方案12】:

                    从JS日期到Mysql日期格式的转换你可以这么简单:

                    date.toISOString().split("T")[0]
                    

                    【讨论】:

                      【解决方案13】:

                      试试这个

                      dateTimeToMYSQL(datx) {
                          var d = new Date(datx),
                            month = '' + (d.getMonth() + 1),
                            day = d.getDate().toString(),
                            year = d.getFullYear(),
                            hours = d.getHours().toString(),
                            minutes = d.getMinutes().toString(),
                            secs = d.getSeconds().toString();
                          if (month.length < 2) month = '0' + month;
                          if (day.length < 2) day = '0' + day;
                          if (hours.length < 2) hours = '0' + hours;
                          if (minutes.length < 2) minutes = '0' + minutes;
                          if (secs.length < 2) secs = '0' + secs;
                          return [year, month, day].join('-') + ' ' + [hours, minutes, secs].join(':');
                        }
                      

                      请注意,您可以删除小时、分钟和秒,结果将显示为 YYYY-MM-DD 优点是在 HTML 表单中输入的日期时间保持不变:不转换为 UTC

                      结果将是(对于您的示例):

                      dateToMYSQL(datx) {
                          var d = new Date(datx),
                            month = '' + (d.getMonth() + 1),
                            day = d.getDate().toString(),
                            year = d.getFullYear();
                          if (month.length < 2) month = '0' + month;
                          if (day.length < 2) day = '0' + day;
                          return [year, month, day].join('-');
                        }
                      

                      【讨论】:

                        【解决方案14】:

                        我想说这可能是最好的方法。刚刚确认它有效:

                        new Date().toISOString().replace('T', ' ').split('Z')[0];
                        

                        【讨论】:

                          猜你喜欢
                          • 1970-01-01
                          • 1970-01-01
                          • 2021-12-31
                          • 1970-01-01
                          • 1970-01-01
                          • 2017-06-24
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          相关资源
                          最近更新 更多