[javascript] How do I format a date as ISO 8601 in moment.js?

This docs mention moment.ISO_8601 as a formatting option (from 2.7.0 - http://momentjs.com/docs/#/parsing/special-formats/), but neither of these work (even 2.7.0):

var date = moment();
date.format(moment.ISO_8601); // error
moment.format(date, moment.ISO_8601); // error

(http://jsfiddle.net/b3d6uy05/1/)

How can I get an ISO 8601 from moment.js?

This question is related to javascript momentjs date-formatting iso8601

The answer is


var date = moment(new Date(), moment.ISO_8601);
console.log(date);

If you just want the date portion (e.g. 2017-06-27), and you want it to work regardless of time zone and also in Arabic, here is code I wrote:

function isoDate(date) {
    if (!date) {
        return null
    }
    date = moment(date).toDate()

    // don't call toISOString because it takes the time zone into
    // account which we don't want.  Also don't call .format() because it
    // returns Arabic instead of English

    var month = 1 + date.getMonth()
    if (month < 10) {
        month = '0' + month
    }
    var day = date.getDate()
    if (day < 10) {
        day = '0' + day
    }
    return date.getFullYear() + '-' + month + '-' + day
}

var x = moment();

//date.format(moment.ISO_8601); // error

moment("2010-01-01T05:06:07", ["YYYY", moment.ISO_8601]);; // error
document.write(x);

Also possible with vanilla JS

new Date().toISOString() // "2017-08-26T16:31:02.349Z"

When you use Mongoose to store dates into MongoDB you need to use toISOString() because all dates are stored as ISOdates with miliseconds.

moment.format() 

2018-04-17T20:00:00Z

moment.toISOString() -> USE THIS TO STORE IN MONGOOSE

2018-04-17T20:00:00.000Z

Answer in 2020 (Includes Timezone Support)

The problem we were having is that, by default, ISOStrings aren't localized to your timezone. So, this is kinda hacky, but here's how we ended up solving this issue:

_x000D_
_x000D_
/** Imports Moment for time utilities. */
const moment = require("moment-timezone")
moment().tz("America/Chicago").format()

//** Returns now in ISO format in Central Time */
export function getNowISO() {
  return `${moment().toISOString(true).substring(0, 23)}Z`
}
_x000D_
_x000D_
_x000D_

This will leave you with an exact ISO-formatted, localized string.

Important note: Moment now suggests using other packages for new projects.


Use format with no parameters:

var date = moment();
date.format(); // "2014-09-08T08:02:17-05:00"

(http://jsfiddle.net/8gvhL1dz/)


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to momentjs

How to get am pm from the date time string using moment js Vuejs and Vue.set(), update array How to subtract one month using moment.js? Get timezone from users browser using moment(timezone).js Check if date is a valid one moment.js get current time in milliseconds? Deprecation warning in Moment.js - Not in a recognized ISO format Moment js get first and last day of current month Moment get current date Moment.js - How to convert date string into date?

Examples related to date-formatting

How to insert date values into table How do I format a date as ISO 8601 in moment.js? Java Convert GMT/UTC to Local time doesn't work as expected Compare two date formats in javascript/jquery How to ISO 8601 format a Date with Timezone Offset in JavaScript? What are the "standard unambiguous date" formats for string-to-date conversion in R? How to convert date in to yyyy-MM-dd Format? Convert timestamp to date in MySQL query Date formatting in WPF datagrid Return date as ddmmyyyy in SQL Server

Examples related to iso8601

How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift? How do I format a date as ISO 8601 in moment.js? Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset) Parsing ISO 8601 date in Javascript How to create a .NET DateTime from ISO 8601 format Illegal pattern character 'T' when parsing a date string to java.util.Date How do I output an ISO 8601 formatted string in JavaScript? Java SimpleDateFormat for time zone with a colon separator? Converting ISO 8601-compliant String to java.util.Date ISO time (ISO 8601) in Python