This seems like a pretty simple question but I can't seem to get an answer for it. How can I convert an iso timestamp to display the date/time using JavaScript?
Example timestamp: 2012-04-15T18:06:08-07:00
Any help is appreciated, Google is failing me. Thank you.
The standard is called ISO-8601 and the format is: YYYY-MM-DDTHH:mm:ss.sssZ.
To convert an ISO date to the date format yyyy-mm-dd with JavaScript, we can call the string substring method. const date = new Date("2022-03-10T02:00:00Z"); const isoDate = date. toISOString(). substring(0, 10);
Use the getTime() method to convert an ISO date to a timestamp, e.g. new Date(isoStr). getTime() . The getTime method returns the number of milliseconds since the Unix Epoch and always uses UTC for time representation. Copied!
“javascript convert iso date to long date” Code Answer'sdate. getFullYear()+'-' + (date. getMonth()+1) + '-'+date. getDate();//prints expected format.
Pass it to the Date constructor.
> var date = new Date('2012-04-15T18:06:08-07:00')
> date
Mon Apr 16 2012 04:06:08 GMT+0300 (EEST)
For more information about Date, check https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date.
The newest version of javascript (v1.85 or higher in some of the latest browsers) can handle the ISO dates directly so you can just pass your string directly to the Date()
constructor like this:
var jsDate = new Date("2012-04-15T18:06:08-07:00");
But older browsers (any version of IE before IE9, any version of Firefox before 4, etc...) do not support this. For those browsers, you can either get a library that can do this for you like datejs or parse it yourself like this:
var t = "2012-04-15T18:06:08-07:00";
function convertDate(t) {
var dateRE = /(\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+)([+\-]\d+):(\d+)/;
var match = t.match(dateRE);
var nums = [], item, date;
if (match) {
for (var i = 1; i < match.length; i++) {
nums.push(parseInt(match[i], 10));
}
if (nums[7] < 0) {
nums[8] *= -1;
}
return(new Date(nums[0], nums[1] - 1, nums[2], nums[3] - nums[6], nums[4] - nums[7], nums[5]));
}
}
var jsDate = convertDate(t);
Working demo here: http://jsfiddle.net/jfriend00/QSgn6/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With