将JavaScript Date对象转换成yyyy-MM-dd HH:mm:ss花样字符串的要领

起首参考文档

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
    2.http://stackoverflow.com/questions/10830357/javascript-toisostring-ignores-timezone-offset

第一种能够立时想到的是运用Date对象的api要领,取得年份,月份,天,小时,分钟和秒数,就能够拼出来。从Date.prototype.toISOString要领轻微革新就能够了:

if (!Date.prototype.toISOString) {
  (function() {

    function pad(number) {
      if (number < 10) {
        return '0' + number;
      }
      return number;
    }

    Date.prototype.toISOString = function() {
      return this.getUTCFullYear() +
        '-' + pad(this.getUTCMonth() + 1) +
        '-' + pad(this.getUTCDate()) +
        ' ' + pad(this.getUTCHours()) +
        ':' + pad(this.getUTCMinutes()) +
        ':' + pad(this.getUTCSeconds())
        ;
    };

  }());
}

另有一种取巧的方法,但不肯定高效:

var d = new Date()
new Date(d.getTime() - d.getTimezoneOffset() * 60000).toISOString().replace("T", " ").replace(/\..+$/,"");
//"2015-12-10 16:11:25"
    原文作者:Honwhy
    原文地址: https://segmentfault.com/a/1190000004126997
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞