How to convert "2016-02-23T11:31:36.23" into JavaScript object?

56 Views Asked by At

I am trying to convert string from the following format into JavaScript Date() object. Then I want to change the format into mm/dd/yyyy h:MM AM/PM using the jquery-dateFormat UI

2016-02-23T11:31:36.23

I tried to do this

    function formatDateTime(str) {

        var dt = new Date(str);

        return $.format.date(dt, "mm/dd/yyyy h:MM TT");
    }

But this is giving me this 00/NaN/NaN NaN:NaN TT

How can I correctly convert the string into a date object?

According to the documentation I should be able to convert isoDateTime into an object just like I have done

1

There are 1 best solutions below

1
On

You can parse de string into a new date and use toLocaleDateString (plain js):

var strdate = "2016-02-23T11:31:36.23";

var date = new Date(Date.parse(strdate));
var options = { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric' };
console.log(date.toLocaleDateString('en-US', options));

Fiddle on: https://jsfiddle.net/fcLkrwv6/