Is there any way to create this string date representation (with timezone) without using javascript substring functions or regular expression?

Starting with the new Date object, is there a way to create the next string representation using only the built-in methods of the Date object, that is, regular expressions or substring manipulations are not allowed? "2013-02-01T00:00:00-05:00"

0
javascript date
Feb 20
source share
2 answers

using only the built-in methods of the Date object

No. JavaScript will not allow you to output ISO 8601 strings with a custom time zone value .toISOSTring always uses Z (UTC).

You will need to use various getter methods and build the string yourself. Based on How to output a string in ISO 8601 format in JavaScript? and How to convert ISOString to local ISOString in javascript? :

 function customISOstring(date, offset) { var date = new Date(date), // copy instance h = Math.floor(Math.abs(offset)/60), m = Math.abs(offset) % 60; date.setMinutes(date.getMinutes() - offset); // apply custom timezone function pad(n) { return n < 10 ? '0' + n : n } return date.getUTCFullYear() + '-' // return custom format + pad(date.getUTCMonth() + 1) + '-' + pad(date.getUTCDate()) + 'T' + pad(date.getUTCHours()) + ':' + pad(date.getUTCMinutes()) + ':' + pad(date.getUTCSeconds()) + (offset==0 ? "Z" : (offset<0 ? "+" : "-") + pad(h) + ":" + pad(m)); } 
+1
Feb 20
source share

This is surprisingly simple, although you will need a helper function to avoid repetition:

 var pad = function(n) {return n < 10 ? "0"+n : n;}; var output = date.getFullYear()+"-"+pad(date.getMonth()+1)+"-"+pad(date.getDate()) +"T"+pad(date.getHours())+":"+pad(date.getMinutes())+":"+pad(date.getSeconds()) +(date.getTimezoneOffset() > 0 ? "-" : "+") +pad(Math.floor(date.getTimezoneOffset()/60)) +":"+pad(date.getTimezoneOffset()%60); 
+2
Feb 20
source share



All Articles