How to Output an Iso 8601 Formatted String in JavaScript

How do I output an ISO 8601 formatted string in JavaScript?

There is already a function called toISOString():

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

If, somehow, you're on a browser that doesn't support it, I've got you covered:

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

}());
}

console.log(new Date().toISOString())

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

Here's a simple helper function that will format JS dates for you.

function toIsoString(date) {
var tzo = -date.getTimezoneOffset(),
dif = tzo >= 0 ? '+' : '-',
pad = function(num) {
return (num < 10 ? '0' : '') + num;
};

return date.getFullYear() +
'-' + pad(date.getMonth() + 1) +
'-' + pad(date.getDate()) +
'T' + pad(date.getHours()) +
':' + pad(date.getMinutes()) +
':' + pad(date.getSeconds()) +
dif + pad(Math.floor(Math.abs(tzo) / 60)) +
':' + pad(Math.abs(tzo) % 60);
}

var dt = new Date();
console.log(toIsoString(dt));

how to Convert Date into ISO Date Format in javascript

You can use String.split() to get the day, month and year for the Date in question.

We can then pass to the Date.UTC() function and then the Date() constructor. (Note: We pass monthIndex to the Date constructor, that's why we subtract 1 from the month )

To display as an ISO string, we can then use Date.toISOString()

const [month, day, year] = '05/23/2022'.split('/');
const date = new Date(Date.UTC(year, month - 1, day));
const result = date.toISOString();
console.log('Date (ISO):', result);

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

moment().toISOString(); // or format() - see below

http://momentjs.com/docs/#/displaying/as-iso-string/

Update
Based on the answer: by @sennet and the comment by @dvlsg (see Fiddle) it should be noted that there is a difference between format and toISOString. Both are correct but the underlying process differs. toISOString converts to a Date object, sets to UTC then uses the native Date prototype function to output ISO8601 in UTC with milliseconds (YYYY-MM-DD[T]HH:mm:ss.SSS[Z]). On the other hand, format uses the default format (YYYY-MM-DDTHH:mm:ssZ) without milliseconds and maintains the timezone offset.

I've opened an issue as I think it can lead to unexpected results.

formating iso 8601 to MMM and hourPM/AM using moment js

You need to pass it the string as YYYY:MM:DDTHH:MM:SS:

const getDateFormatted = str => {
const date = str.slice(0,19);
return moment(date).format("MMM DD - h a");
}
console.log( getDateFormatted("2021-01-16T03:00:000Z") );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous"></script>

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

Simple way:

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

How to convert an ISO date to the date format yyyy-mm-dd?

Try this

date = new Date('2013-03-10T02:00:00Z');
date.getFullYear()+'-' + (date.getMonth()+1) + '-'+date.getDate();//prints expected format.

Update:-

As pointed out in comments, I am updating the answer to print leading zeros for date and month if needed.

date = new Date('2013-08-03T02:00:00Z');year = date.getFullYear();month = date.getMonth()+1;dt = date.getDate();
if (dt < 10) { dt = '0' + dt;}if (month < 10) { month = '0' + month;}
console.log(year+'-' + month + '-'+dt);

How can I format an ISO 8601 date to a more readable format, using Javascript?

The easiest would be to just work with the string

$(data).each(function(){

var date = this.created_at.split('T') // split on the "T" -> ["2015-11-09", "10:..."]
.shift() // get the first part -> "2015-11-09"
.split('-') // split again on "-" -> ["2015", "11", "09"]
.reverse() // reverse the array -> ["09", "11", "2015"]
.join('/') // join with "/" -> "09/11/2015"

var html = '<randomhtml> ' + date + ' <randomhtml>';
$('#stream').append(html);
});

As it's a UTC date, just passing it do new Date() would add the difference of the timezone, and not always output the correct date.

If you need to validate the date, there are regexes for checking valid UTC dates.



Related Topics



Leave a reply



Submit