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

JavascriptDateIso8601

Javascript Problem Overview


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

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

Javascript Solutions


Solution 1 - Javascript

Simple way:

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

Solution 2 - Javascript

Use slice to remove the undesired part

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

Solution 3 - Javascript

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.

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

Solution 4 - Javascript

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

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

console.log(date);

Solution 5 - Javascript

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

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';
};

Solution 6 - Javascript

It is similar to @STORM's answer:

const date = new Date();

console.log(date.toISOString());
console.log(date.toISOString().replace(/[.]\d+/, ''));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbessarabovView Question on Stackoverflow
Solution 1 - JavascriptBlue Eyed BehemothView Answer on Stackoverflow
Solution 2 - JavascriptsdespontView Answer on Stackoverflow
Solution 3 - JavascriptSTORMView Answer on Stackoverflow
Solution 4 - JavascriptGrant MillerView Answer on Stackoverflow
Solution 5 - JavascriptAramView Answer on Stackoverflow
Solution 6 - JavascriptnonopolarityView Answer on Stackoverflow