jQuery UI $.datepicker.formatDate returns NaN NaN Nan

2.9k views Asked by At

I have a mySql table, in which there's a column called posted, that is set to type timestamp and defaults to current_timestamp. I then usen php PDO to get the value of it (along with a few other columns), and echo json_encode the whole thing. I call my .php file using an AJAX call, and now I want to format the date I receive.

Some googling resulted in me adding jQuery-UI for its $.datepicker function, as an easy way to format data. Since I'm probably going to be using some other jQuery-UI elements on my page, this seems like a reasonable solution. So far I've been unable to get it working though.

When I console.log the relevant object, I get this result "2015-06-10 13:26:54".

Here's my JS code (you should be looking at var posted):

function makeArticleFeed(response) {
        $('#articles-feed').empty();
        if(response.length > 0) {
            for(var x = 0; x<response.length; x++) {
                console.log(response[x].posted);
                var posted = $.datepicker.formatDate('dd m yy', new Date(response[x].posted)); 
                $("#articles-feed").append(
                    '<div class="article-box"><h1><a href="#">'+response[x].title+
                    '</a></h1><h3><a href="#">' +response[x].author_id+
                    '</a>&nbsp;|&nbsp;'+ posted+
                    '</h3><p>'+response[x].extract+'</p></div>'
                    );
            } //end article feed for loop
        } 
        else {
            $("#articles-feed").append('<h1>Sorry, no article found!</h1>');
        }
1

There are 1 answers

1
adeneo On BEST ANSWER

That's what you get when you pass the string Invalid Date to the formatDate() function.

In other words, response[x].posted is not a valid date that can be parsed by javascripts new Date.

If it's a timestamp from MySQL, it's generally in the format 2015-06-11 16:48:24 and you can get epoch time in most serverside languanges, for instance just passing it to PHP's strtotime would work, and then you'd have seconds from epoch, and javascript accepts milliseconds so you'd multiply by a thousand either on the server or before passing it to new Date.