首页 文章

如何在JavaScript中输出ISO 8601格式的字符串?

提问于
浏览
234

我有一个 Date 对象 . How do I render the title portion of the following snippet?

<abbr title="2010-04-02T14:12:07">A couple days ago</abbr>

我有另一个图书馆的"relative time in words"部分 .

我尝试过以下方法:

function isoDate(msSinceEpoch) {

   var d = new Date(msSinceEpoch);
   return d.getUTCFullYear() + '-' + (d.getUTCMonth() + 1) + '-' + d.getUTCDate() + 'T' +
          d.getUTCHours() + ':' + d.getUTCMinutes() + ':' + d.getUTCSeconds();

}

但这给了我:

"2010-4-2T3:19"

14 回答

  • 23
    function timeStr(d) { 
      return ''+
        d.getFullYear()+
        ('0'+(d.getMonth()+1)).slice(-2)+
        ('0'+d.getDate()).slice(-2)+
        ('0'+d.getHours()).slice(-2)+
        ('0'+d.getMinutes()).slice(-2)+
        ('0'+d.getSeconds()).slice(-2);
    }
    
  • 2

    'T'之后有一个''缺失'

    isoDate: function(msSinceEpoch) {
      var d = new Date(msSinceEpoch);
      return d.getUTCFullYear() + '-' + (d.getUTCMonth() + 1) + '-' + d.getUTCDate() + 'T'
             + d.getUTCHours() + ':' + d.getUTCMinutes() + ':' + d.getUTCSeconds();
    }
    

    应该这样做 .

    对于前导零,您可以使用here

    function PadDigits(n, totalDigits) 
    { 
        n = n.toString(); 
        var pd = ''; 
        if (totalDigits > n.length) 
        { 
            for (i=0; i < (totalDigits-n.length); i++) 
            { 
                pd += '0'; 
            } 
        } 
        return pd + n.toString(); 
    }
    

    像这样使用它:

    PadDigits(d.getUTCHours(),2)
    
  • 63

    已有一个名为toISOString()的函数:

    var date = new Date();
    date.toISOString(); //"2011-12-19T15:28:46.493Z"
    

    如果,不知何故,你在a browser上没有让你满意:

    if ( !Date.prototype.toISOString ) {
      ( function() {
    
        function pad(number) {
          var r = String(number);
          if ( r.length === 1 ) {
            r = '0' + r;
          }
          return r;
        }
    
        Date.prototype.toISOString = function() {
          return this.getUTCFullYear()
            + '-' + pad( this.getUTCMonth() + 1 )
            + '-' + pad( this.getUTCDate() )
            + 'T' + pad( this.getUTCHours() )
            + ':' + pad( this.getUTCMinutes() )
            + ':' + pad( this.getUTCSeconds() )
            + '.' + String( (this.getUTCMilliseconds()/1000).toFixed(3) ).slice( 2, 5 )
            + 'Z';
        };
    
      }() );
    }
    
  • 0

    请参阅第https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference:Global_Objects:Date页上的最后一个示例:

    /* Use a function for the exact format desired... */
    function ISODateString(d) {
        function pad(n) {return n<10 ? '0'+n : n}
        return d.getUTCFullYear()+'-'
             + pad(d.getUTCMonth()+1)+'-'
             + pad(d.getUTCDate())+'T'
             + pad(d.getUTCHours())+':'
             + pad(d.getUTCMinutes())+':'
             + pad(d.getUTCSeconds())+'Z'
    }
    
    var d = new Date();
    console.log(ISODateString(d)); // Prints something like 2009-09-28T19:03:12Z
    
  • 2

    Web上几乎每个to-ISO方法都会在输出字符串之前通过应用转换为“Z”ulu时间(UTC)来丢弃时区信息 . 浏览器的原生.toISOString()也会删除时区信息 .

    这会丢弃有 Value 的信息,因为服务器或收件人始终可以将完整的ISO日期转换为Zulu时间或其所需的时区,同时仍然可以获取发件人的时区信息 .

    我遇到的最佳解决方案是使用 Moment.js javascript库并使用以下代码:

    使用时区信息和毫秒获取当前ISO时间

    now = moment().format("YYYY-MM-DDTHH:mm:ss.SSSZZ")
    // "2013-03-08T20:11:11.234+0100"
    
    now = moment().utc().format("YYYY-MM-DDTHH:mm:ss.SSSZZ")
    // "2013-03-08T19:11:11.234+0000"
    
    now = moment().utc().format("YYYY-MM-DDTHH:mm:ss") + "Z"
    // "2013-03-08T19:11:11Z" <- better use the native .toISOString()
    

    获取具有时区信息但没有毫秒的本机JavaScript Date对象的ISO时间

    var current_time = Date.now();
    moment(current_time).format("YYYY-MM-DDTHH:mm:ssZZ")
    

    这可以与Date.js结合使用以获取Date.today()等函数,然后将其结果传递给片刻 .

    像这样格式化的日期字符串是JSON编译器,并且非常适合存储到数据库中 . Python和C#似乎喜欢它 .

  • 419

    提出的问题是ISO格式,精度降低 . 瞧:

    new Date().toISOString().slice(0, 19) + 'Z'
     // '2014-10-23T13:18:06Z'
    

    假设需要尾随Z,否则只省略 .

  • 58

    如果您不需要支持IE7,以下是一个非常简洁的黑客:

    JSON.parse(JSON.stringify(new Date()))
    
  • 12

    最短但不受Internet Explorer 8及更早版本的支持:

    new Date().toJSON()
    
  • 3

    我通常不喜欢在头脑中进行转换 . 要显示 local ISO日期,我使用以下功能:

    function toLocalIsoString(date, includeSeconds) {
        function pad(n) { return n < 10 ? '0' + n : n }
        var localIsoString = date.getFullYear() + '-'
            + pad(date.getMonth() + 1) + '-'
            + pad(date.getDate()) + 'T'
            + pad(date.getHours()) + ':'
            + pad(date.getMinutes()) + ':'
            + pad(date.getSeconds());
        if(date.getTimezoneOffset() == 0) localIsoString += 'Z';
        return localIsoString;
    };
    

    上面的函数省略了时区偏移信息(除非本地时间恰好是UTC),所以我使用下面的函数在一个位置显示本地偏移量 . 如果您希望每次都显示偏移量,也可以将其输出附加到上述函数的结果中:

    function getOffsetFromUTC() {
        var offset = new Date().getTimezoneOffset();
        return ((offset < 0 ? '+' : '-')
            + pad(Math.abs(offset / 60), 2)
            + ':'
            + pad(Math.abs(offset % 60), 2))
    };
    

    toLocalIsoString 使用 pad . 如果需要,它几乎可以像任何pad功能一样工作,但为了完整起见,这就是我使用的:

    // Pad a number to length using padChar
    function pad(number, length, padChar) {
        if (typeof length === 'undefined') length = 2;
        if (typeof padChar === 'undefined') padChar = '0';
        var str = "" + number;
        while (str.length < length) {
            str = padChar + str;
        }
        return str;
    }
    
  • 11

    toISOString的问题在于它只将datetime作为“Z” .

    ISO-8601还定义了具有时区差异的日期时间,以小时和分钟为单位,形式如2016-07-16T19:20:30 5:30(当时区提前UTC时)和2016-07-16T19:20:30-01: 00(当时区落后于UTC时) .

    我不认为使用另一个插件,moment.js来完成这么小的任务是个好主意,特别是当你能用几行代码获得它时 .

    var timezone_offset_min = new Date().getTimezoneOffset(),
            offset_hrs = parseInt(Math.abs(timezone_offset_min/60)),
            offset_min = Math.abs(timezone_offset_min%60),
            timezone_standard;
    
        if(offset_hrs < 10)
            offset_hrs = '0' + offset_hrs;
    
        if(offset_min > 10)
            offset_min = '0' + offset_min;
    
        // getTimezoneOffset returns an offset which is positive if the local timezone is behind UTC and vice-versa.
        // So add an opposite sign to the offset
        // If offset is 0, it means timezone is UTC
        if(timezone_offset_min < 0)
            timezone_standard = '+' + offset_hrs + ':' + offset_min;
        else if(timezone_offset_min > 0)
            timezone_standard = '-' + offset_hrs + ':' + offset_min;
        else if(timezone_offset_min == 0)
            timezone_standard = 'Z';
    
        // Timezone difference in hours and minutes
        // String such as +5:30 or -6:00 or Z
        console.log(timezone_standard);
    

    一旦你有以小时和分钟为单位的时区偏移量,你就可以附加到日期时间字符串 .

    我在上面写了一篇博文:http://usefulangle.com/post/30/javascript-get-date-time-with-offset-hours-minutes

  • 6

    我只想使用这个小扩展 Date - http://blog.stevenlevithan.com/archives/date-time-format

    var date = new Date(msSinceEpoch);
    date.format("isoDateTime"); // 2007-06-09T17:46:21
    
  • 3

    我能够以非常少的代码获得低于输出 .

    var ps = new Date('2010-04-02T14:12:07')  ;
    ps = ps.toDateString() + " " + ps.getHours() + ":"+ ps.getMinutes() + " hrs";
    

    输出:

    Fri Apr 02 2010 19:42 hrs
    
  • 3
    function getdatetime() {
        d = new Date();
        return (1e3-~d.getUTCMonth()*10+d.toUTCString()+1e3+d/1)
            .replace(/1(..)..*?(\d+)\D+(\d+).(\S+).*(...)/,'$3-$1-$2T$4.$5Z')
            .replace(/-(\d)T/,'-0$1T');
    }
    

    我在某处找到了Stack Overflow的基础知识(我相信它是其他一些Stack Exchange代码打包的一部分),我对它进行了改进,因此它也适用于Internet Explorer 10或更早版本 . 这很丑陋,但它完成了工作 .

  • 0

    用一些糖和现代语法扩展Sean的精彩和简洁的答案:

    // date.js
    
    const getMonthName = (num) => {
      const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Oct', 'Nov', 'Dec'];
      return months[num];
    };
    
    const formatDate = (d) => {
      const date = new Date(d);
      const year = date.getFullYear();
      const month = getMonthName(date.getMonth());
      const day = ('0' + date.getDate()).slice(-2);
      const hour = ('0' + date.getHours()).slice(-2);
      const minutes = ('0' + date.getMinutes()).slice(-2);
    
      return `${year} ${month} ${day}, ${hour}:${minutes}`;
    };
    
    module.exports = formatDate;
    

    然后例如 .

    import formatDate = require('./date');
    
    const myDate = "2018-07-24T13:44:46.493Z"; // Actual value from wherever, eg. MongoDB date
    console.log(formatDate(myDate)); // 2018 Jul 24, 13:44
    

相关问题