dave
dave

Reputation: 205

Converting Date time formats

What's the best way to convert date time formats using javascript?

I have this.. "2015-08-06T00:39:08Z" and would like to change it to

"06/08/2015 12:39pm"

Upvotes: 0

Views: 90

Answers (3)

EugenSunic
EugenSunic

Reputation: 13693

With pure javascript:

code:

function formatDate(input) {
    var datePart = input.match(/\d+/g),
        year = datePart[0], // get only two digits
        month = datePart[1],
        day = datePart[2];
    var h = parseInt(input.substr(input.indexOf("T") + 1, 2));
    var m = parseInt(input.substr(input.indexOf(":") + 1, 2));
    var dd = "AM";
    if (h >= 12) {
        h = hh - 12;
        dd = "PM";
    }
    if (h == 0) {
        h = 12;
    }
    m = m < 10 ? "0" + m : m;
    alert(day + '/' + month + '/' + year + ' ' + h.toString() + ':' + m.toString() + dd);
}

formatDate('2015-08-06T00:39:08Z'); // "18/01/10"

Upvotes: 1

anam
anam

Reputation: 216

Use newDate() method, then Date Get Methods. Examples are explained on w3Schools

Method Description

            getDate()   Get the day as a number (1-31)
            getDay()    Get the weekday as a number (0-6)
            getFullYear()   Get the four digit year (yyyy)
            getHours()  Get the hour (0-23)
            getMilliseconds()   Get the milliseconds (0-999)
            getMinutes()    Get the minutes (0-59)
            getMonth()  Get the month (0-11)
            getSeconds()    Get the seconds (0-59)
            getTime()   Get the time (milliseconds since January 1, 1970)

Upvotes: 1

Benoit
Benoit

Reputation: 791

You could do it manually by instantiating a Date object:

var d = new Date('2015-08-06T00:39:08Z');

Then using the Date methods (like getDay or getUTCFullYear) to get the information needed and build the formatted string.

Or, if you don't mind relying on a library, you could use http://momentjs.com/ that provides a lot of methods, and particularly the format method: http://momentjs.com/docs/#/displaying/format/

// Example with moment.js
var formattedDate = moment('2015-08-06T00:39:08Z').format("MM/DD/YYYY hh:mma");
alert(formattedDate);

Upvotes: 1

Related Questions