【问题标题】:Convert JS date time to MySQL datetime将 JS 日期时间转换为 MySQL 日期时间
【发布时间】:2011-07-05 00:24:50
【问题描述】:

有谁知道如何将 JS 日期时间转换为 MySQL 日期时间?还有没有办法给 JS 日期时间添加特定的分钟数,然后将其传递给 MySQL 日期时间?

【问题讨论】:

    标签: javascript mysql


    【解决方案1】:
    var date;
    date = new Date();
    date = date.getUTCFullYear() + '-' +
        ('00' + (date.getUTCMonth()+1)).slice(-2) + '-' +
        ('00' + date.getUTCDate()).slice(-2) + ' ' + 
        ('00' + date.getUTCHours()).slice(-2) + ':' + 
        ('00' + date.getUTCMinutes()).slice(-2) + ':' + 
        ('00' + date.getUTCSeconds()).slice(-2);
    console.log(date);
    

    甚至更短:

    new Date().toISOString().slice(0, 19).replace('T', ' ');
    

    输出:

    2012-06-22 05:40:06
    

    对于更高级的用例,包括控制时区,请考虑使用http://momentjs.com/

    require('moment')().format('YYYY-MM-DD HH:mm:ss');
    

    对于 的轻量级替代方案,请考虑https://github.com/taylorhakes/fecha

    require('fecha').format('YYYY-MM-DD HH:mm:ss')
    

    【讨论】:

    • 在 date.getUTCDate 之前有一个额外的左括号,是的,这样更好。
    • 这会因时区问题而出问题
    • 把时区设置丢了,怎么保留?
    • 将其与此组合以处理时区:stackoverflow.com/questions/11887934/…
    • 使用时区 oneliner 的完整解决方法!! var d = new Date(); d.toISOString().split('T')[0]+' '+d.toTimeString().split(' ')[0];
    【解决方案2】:

    我认为使用toISOString()方法可以使解决方案不那么笨拙,它具有广泛的浏览器兼容性。

    所以你的表达将是单行的:

    new Date().toISOString().slice(0, 19).replace('T', ' ');
    

    生成的输出:

    “2017-06-29 17:54:04”

    【讨论】:

    • 工作出色! new Date(1091040026000).toISOString().slice(0, 19).replace('T', ' ');
    • 太好了,这里只有一个问题:更笨重的方法是获取 js Date's 之后的小时、日、月(偶数年) i>时区偏移。而您的以 MySQL DATETIME 格式返回底层 UTC 时间。在大多数情况下,存储 UTC 可能会更好,无论哪种情况,您的数据表都应该在一个字段中提供位置信息。或者,转换为本地时间非常简单:使用... - Date.getTimezoneOffset() * 60 * 1000(NB 还会在适用的情况下调整夏令时)。
    【解决方案3】:

    虽然 JS 确实拥有足够的基本工具来执行此操作,但它相当笨重。

    /**
     * You first need to create a formatting function to pad numbers to two digits…
     **/
    function twoDigits(d) {
        if(0 <= d && d < 10) return "0" + d.toString();
        if(-10 < d && d < 0) return "-0" + (-1*d).toString();
        return d.toString();
    }
    
    /**
     * …and then create the method to output the date string as desired.
     * Some people hate using prototypes this way, but if you are going
     * to apply this to more than one Date object, having it as a prototype
     * makes sense.
     **/
    Date.prototype.toMysqlFormat = function() {
        return this.getUTCFullYear() + "-" + twoDigits(1 + this.getUTCMonth()) + "-" + twoDigits(this.getUTCDate()) + " " + twoDigits(this.getUTCHours()) + ":" + twoDigits(this.getUTCMinutes()) + ":" + twoDigits(this.getUTCSeconds());
    };
    

    【讨论】:

    • 如何用变量调用这样的函数?
    • @Catfish 你的意思是有一个具体的日期?您使用 Date 对象。 new Date().toMysqlFormat()new Date(2014,12,14).toMysqlFormat() 或其他。
    • 这个答案在 JavaScript 陈旧而笨重的时候就有了。如果你的目标是现代浏览器,我推荐Gajus' toISOString approach
    【解决方案4】:

    MySQL 的 JS 时间值

    var datetime = new Date().toLocaleString();
    

    const DATE_FORMATER = require( 'dateformat' );
    var datetime = DATE_FORMATER( new Date(), "yyyy-mm-dd HH:MM:ss" );
    

    const MOMENT= require( 'moment' );
    let datetime = MOMENT().format( 'YYYY-MM-DD  HH:mm:ss.000' );
    

    你可以在参数中发送它,它会起作用。

    【讨论】:

    • toLocaleString() 取决于语言环境。可能有些地方和mysql一样,但是一般来说确实不是个好办法
    【解决方案5】:

    对于任意日期字符串,

    // Your default date object  
    var starttime = new Date();
    // Get the iso time (GMT 0 == UTC 0)
    var isotime = new Date((new Date(starttime)).toISOString() );
    // getTime() is the unix time value, in milliseconds.
    // getTimezoneOffset() is UTC time and local time in minutes.
    // 60000 = 60*1000 converts getTimezoneOffset() from minutes to milliseconds. 
    var fixedtime = new Date(isotime.getTime()-(starttime.getTimezoneOffset()*60000));
    // toISOString() is always 24 characters long: YYYY-MM-DDTHH:mm:ss.sssZ.
    // .slice(0, 19) removes the last 5 chars, ".sssZ",which is (UTC offset).
    // .replace('T', ' ') removes the pad between the date and time.
    var formatedMysqlString = fixedtime.toISOString().slice(0, 19).replace('T', ' ');
    console.log( formatedMysqlString );
    

    或单线解决方案,

    var formatedMysqlString = (new Date ((new Date((new Date(new Date())).toISOString() )).getTime() - ((new Date()).getTimezoneOffset()*60000))).toISOString().slice(0, 19).replace('T', ' ');
    console.log( formatedMysqlString );
    

    在 mysql 中使用 Timestamp 时,此解决方案也适用于 Node.js。

    @Gajus Kuizinas's first answer seems to modify mozilla's toISOString prototype

    【讨论】:

      【解决方案6】:
      new Date().toISOString().slice(0, 10)+" "+new Date().toLocaleTimeString('en-GB');
      

      【讨论】:

        【解决方案7】:

        我想到的将 JS 日期转换为 SQL 日期时间格式的最简单正确的方法就是这个。它正确处理时区偏移。

        const toSqlDatetime = (inputDate) => {
            const date = new Date(inputDate)
            const dateWithOffest = new Date(date.getTime() - (date.getTimezoneOffset() * 60000))
            return dateWithOffest
                .toISOString()
                .slice(0, 19)
                .replace('T', ' ')
        }
        
        toSqlDatetime(new Date()) // 2019-08-07 11:58:57
        toSqlDatetime(new Date('2016-6-23 1:54:16')) // 2016-06-23 01:54:16
        

        注意@Paulo Roberto answer 在新的一天会产生错误的结果(我不能离开 cmets)。例如

        var d = new Date('2016-6-23 1:54:16'),
            finalDate = d.toISOString().split('T')[0]+' '+d.toTimeString().split(' ')[0];
        console.log(finalDate); // 2016-06-22 01:54:16 
        

        我们现在是 6 月 22 日而不是 23 日!

        【讨论】:

        • 像魅力一样工作!
        【解决方案8】:

        古老的DateJS 库有一个格式化例程(它覆盖了“.toString()”)。你也可以很容易地自己做一个,因为“日期”方法为你提供了你需要的所有数字。

        【讨论】:

          【解决方案9】:

          简短版:

          // JavaScript timestamps need to be converted to UTC time to match MySQL
          
          // MySQL formatted UTC timestamp +30 minutes
          let d = new Date()
          let mySqlTimestamp = new Date(
            d.getFullYear(),
            d.getMonth(),
            d.getDate(),
            d.getHours(),
            (d.getMinutes() + 30), // add 30 minutes
            d.getSeconds(),
            d.getMilliseconds()
          ).toISOString().slice(0, 19).replace('T', ' ')
          
          console.log("MySQL formatted UTC timestamp: " + mySqlTimestamp)

          UTC 时间通常是在 MySQL 中存储时间戳的最佳选择。如果您没有 root 访问权限,请在连接开始时运行 set time_zone = '+00:00'

          在 MySQL 中使用 convert_tz 方法显示特定时区的时间戳

          select convert_tz(now(), 'SYSTEM', 'America/Los_Angeles');
          

          JavaScript 时间戳基于您设备的时钟并包含时区。在发送从 JavaScript 生成的任何时间戳之前,您应该将它们转换为 UTC 时间。 JavaScript 有一个名为 toISOString() 的方法,它将 JavaScript 时间戳格式化为类似于 MySQL 时间戳,并将时间戳转换为 UTC 时间。最后的清理使用切片和替换进行。

          let timestmap = new Date()
          timestmap.toISOString().slice(0, 19).replace('T', ' ')
          

          长版显示正在发生的事情:

          // JavaScript timestamps need to be converted to UTC time to match MySQL
          
          // local timezone provided by user's device
          let d = new Date()
          console.log("JavaScript timestamp: " + d.toLocaleString())
          
          // add 30 minutes
          let add30Minutes = new Date(
            d.getFullYear(),
            d.getMonth(),
            d.getDate(),
            d.getHours(),
            (d.getMinutes() + 30), // add 30 minutes
            d.getSeconds(),
            d.getMilliseconds()
          )
          console.log("Add 30 mins: " + add30Minutes.toLocaleString())
          
          // ISO formatted UTC timestamp
          // timezone is always zero UTC offset, as denoted by the suffix "Z"
          let isoString = add30Minutes.toISOString()
          console.log("ISO formatted UTC timestamp: " + isoString)
          
          // MySQL formatted UTC timestamp: YYYY-MM-DD HH:MM:SS
          let mySqlTimestamp = isoString.slice(0, 19).replace('T', ' ')
          console.log("MySQL formatted UTC timestamp: " + mySqlTimestamp)

          【讨论】:

            【解决方案10】:

            使用@Gajus 回答概念的完整解决方法(维护时区):

            var d = new Date(),
                finalDate = d.toISOString().split('T')[0]+' '+d.toTimeString().split(' ')[0];
            console.log(finalDate); //2018-09-28 16:19:34 --example output
            

            【讨论】:

            • 这只会在时间上维护时区,而不是在日期上。
            【解决方案11】:

            我给出了简单的 JavaScript 日期格式示例,请查看下面的代码

            var data = new Date($.now()); // without jquery remove this $.now()
            console.log(data)// Thu Jun 23 2016 15:48:24 GMT+0530 (IST)
            
            var d = new Date,
                dformat = [d.getFullYear() ,d.getMonth()+1,
                           d.getDate()
                           ].join('-')+' '+
                          [d.getHours(),
                           d.getMinutes(),
                           d.getSeconds()].join(':');
            
            console.log(dformat) //2016-6-23 15:54:16
            

            使用momentjs

            var date = moment().format('YYYY-MM-DD H:mm:ss');
            
            console.log(date) // 2016-06-23 15:59:08
            

            示例请查看https://jsfiddle.net/sjy3vjwm/2/

            【讨论】:

            • 我刚刚用香草 javascript 尝试了你的第一个代码,它给了我这个结果:2018-4-20 15:11:23。您没有用前导“0”填充数字。另外,我不知道momentjs,但您不必将“HH”放一个小时以便填充它吗?也许这就是你被否决的原因? (itwasntme)
            【解决方案12】:
            var _t = new Date();
            

            如果你只是想要 UTC 格式

            _t.toLocaleString('indian', { timeZone: 'UTC' }).replace(/(\w+)\/(\w+)\/(\w+), (\w+)/, '$3-$2-$1 $4');
            

            _t.toISOString().slice(0, 19).replace('T', ' ');
            

            如果想要在特定时区,那么

            _t.toLocaleString('indian', { timeZone: 'asia/kolkata' }).replace(/(\w+)\/(\w+)\/(\w+), (\w+)/, '$3-$2-$1 $4');
            

            【讨论】:

              【解决方案13】:

              一个简单的解决方案是向 MySQL 发送时间戳并让它进行转换。 Javascript 以毫秒为单位使用时间戳,而 MySQL 期望它们以秒为单位 - 所以需要除以 1000:

              // Current date / time as a timestamp:
              let jsTimestamp = Date.now();
              
              // **OR** a specific date / time as a timestamp:
              jsTimestamp = new Date("2020-11-17 16:34:59").getTime();
              
              // Adding 30 minutes (to answer the second part of the question):
              jsTimestamp += 30 * 1000;
              
              // Example query converting Javascript timestamp into a MySQL date
              let sql = 'SELECT FROM_UNIXTIME(' + jsTimestamp + ' / 1000) AS mysql_date_time';
              

              【讨论】:

                【解决方案14】:

                使用toJSON()日期函数如下:

                var sqlDatetime = new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60 * 1000).toJSON().slice(0, 19).replace('T', ' ');
                console.log(sqlDatetime);

                【讨论】:

                  【解决方案15】:

                  这是迄今为止我能想到的最简单的方法

                  new Date().toISOString().slice(0, 19).replace("T", " ")
                  

                  【讨论】:

                    【解决方案16】:

                    我用了这么久,对我很有帮助,你喜欢用什么

                    Date.prototype.date=function() {
                        return this.getFullYear()+'-'+String(this.getMonth()+1).padStart(2, '0')+'-'+String(this.getDate()).padStart(2, '0')
                    }
                    
                    Date.prototype.time=function() {
                        return String(this.getHours()).padStart(2, '0')+':'+String(this.getMinutes()).padStart(2, '0')+':'+String(this.getSeconds()).padStart(2, '0')
                    }
                    
                    Date.prototype.dateTime=function() {
                        return this.getFullYear()+'-'+String(this.getMonth()+1).padStart(2, '0')+'-'+String(this.getDate()).padStart(2, '0')+' '+String(this.getHours()).padStart(2, '0')+':'+String(this.getMinutes()).padStart(2, '0')+':'+String(this.getSeconds()).padStart(2, '0')
                    }
                    
                    Date.prototype.addTime=function(time) {
                        var time=time.split(":")
                        var rd=new Date(this.setHours(this.getHours()+parseInt(time[0])))
                        rd=new Date(rd.setMinutes(rd.getMinutes()+parseInt(time[1])))
                        return new Date(rd.setSeconds(rd.getSeconds()+parseInt(time[2])))
                    }
                    
                    Date.prototype.addDate=function(time) {
                        var time=time.split("-")
                        var rd=new Date(this.setFullYear(this.getFullYear()+parseInt(time[0])))
                        rd=new Date(rd.setMonth(rd.getMonth()+parseInt(time[1])))
                        return new Date(rd.setDate(rd.getDate()+parseInt(time[2])))
                    }
                    
                    Date.prototype.subDate=function(time) {
                        var time=time.split("-")
                        var rd=new Date(this.setFullYear(this.getFullYear()-parseInt(time[0])))
                        rd=new Date(rd.setMonth(rd.getMonth()-parseInt(time[1])))
                        return new Date(rd.setDate(rd.getDate()-parseInt(time[2])))
                    }
                    

                    然后只是:

                    new Date().date()
                    

                    以“MySQL 格式”返回当前日期

                    添加时间是

                    new Date().addTime('0:30:0')
                    

                    这将增加 30 分钟......等等

                    【讨论】:

                      【解决方案17】:

                      基于其他答案构建的解决方案,同时保持时区和前导零:

                      var d = new Date;
                      
                      var date = [
                          d.getFullYear(),
                          ('00' + d.getMonth() + 1).slice(-2),
                          ('00' + d.getDate() + 1).slice(-2)
                      ].join('-');
                      
                      var time = [
                          ('00' + d.getHours()).slice(-2),
                          ('00' + d.getMinutes()).slice(-2),
                          ('00' + d.getSeconds()).slice(-2)
                      ].join(':');
                      
                      var dateTime = date + ' ' + time;
                      console.log(dateTime) // 2021-01-41 13:06:01
                      

                      【讨论】:

                        【解决方案18】:

                        简单:只需替换 T。 我从

                        所以只需替换 T,它看起来像这样:“2021-02-10 18:18”SQL 会吃掉它。

                        这是我的功能:

                        var CreatedTime = document.getElementById("example-datetime-local-input").value;

                        var newTime = CreatedTime.replace("T", "");

                        参考: https://www.tutorialrepublic.com/faq/how-to-replace-character-inside-a-string-in-javascript.php#:~:text=Answer%3A%20Use%20the%20JavaScript%20replace,the%20global%20(%20g%20)%20modifier.

                        https://www.tutorialrepublic.com/codelab.php?topic=faq&file=javascript-replace-character-in-a-string

                        【讨论】:

                          猜你喜欢
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 2015-03-23
                          • 2011-11-11
                          • 1970-01-01
                          相关资源
                          最近更新 更多