Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert iso timestamp to date format with Javascript?

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.

like image 386
Ian Avatar asked Apr 16 '12 21:04

Ian


People also ask

What is ISO date format in JavaScript?

The standard is called ISO-8601 and the format is: YYYY-MM-DDTHH:mm:ss.sssZ.

How do I convert ISO date to mm dd yyyy?

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);

How do I convert ISO to timestamp?

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!

How do I convert ISO date to long date?

“javascript convert iso date to long date” Code Answer'sdate. getFullYear()+'-' + (date. getMonth()+1) + '-'+date. getDate();//prints expected format.


2 Answers

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.

like image 98
eagleflo Avatar answered Oct 07 '22 17:10

eagleflo


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/

like image 39
jfriend00 Avatar answered Oct 07 '22 16:10

jfriend00