如何在没有毫秒和 Z 的情况下在 ISO 8601 中的 javascript 中输出日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34053715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:52:11  来源:igfitidea点击:

How to output date in javascript in ISO 8601 without milliseconds and with Z

javascriptdateiso8601

提问by bessarabov

Here is a standard way to serialise date as ISO 8601 string in JavaScript:

这是在 JavaScript 中将日期序列化为 ISO 8601 字符串的标准方法:

var now = new Date();
console.log( now.toISOString() );
// outputs '2015-12-02T21:45:22.279Z'

I need just the same output, but without milliseconds. How can I output 2015-12-02T21:45:22Z

我只需要相同的输出,但没有毫秒。我怎样才能输出2015-12-02T21:45:22Z? 

回答by Blue Eyed Behemoth

Simple way:

简单的方法:

console.log( now.toISOString().split('.')[0]+"Z" );

回答by STORM

This is the solution:

这是解决方案:

var now = new Date(); 
var str = now.toISOString();
var res = str.replace(/\.[0-9]{3}/, '');
alert(res);

Finds the . (dot) and removes 3 characters.

找到 . (点)并删除 3 个字符。

http://jsfiddle.net/boglab/wzudeyxL/7/

http://jsfiddle.net/boglab/wzudeyxL/7/

回答by sdespont

Use slice to remove the undesired part

使用切片去除不需要的部分

var now = new Date();
alert( now.toISOString().slice(0,-5)+"Z");

回答by Grant Miller

You can use a combination of split()and shift()to remove the milliseconds from an ISO 8601string:

您可以使用的组合split()以及shift()从一个删除毫秒ISO 8601字符串:

let date = new Date().toISOString().split('.').shift() + 'Z';

console.log(date);

回答by Aram

or probably overwrite it with this? (this is a modified polyfill from here)

或者可能用这个覆盖它?(这是从这里修改的 polyfill )

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()) +
    'T' + pad(this.getUTCHours()) +
    ':' + pad(this.getUTCMinutes()) +
    ':' + pad(this.getUTCSeconds()) +
    'Z';
};