Jerome
Jerome

Reputation: 9

Format date output from array loop in Javascript

I have a 2D array containing a date object and a string. I output the array to an HTML table using a for loop. This works fine, but I need to change the date format from "2015-12-02 00:00" to "Wed Dec 02 2015". The array must remain a date object, but I can not figure out how to use dateFormat or moment.js functions within the loop. What am I doing wrong?

var tasks = new Array();
var index = 0;


function addTask() {
    var tempdate = new Date();
    var temptask = document.getElementById("taskinfo").value;
    var td = document.getElementById("taskdate").value;
    tempdate = td + " 00:00";

//window.alert(temptask);
//add array and populate from tempdate and temptask
//generate html table from 2d javascript array
    tasks[index] = {
    Date: tempdate,
    Task: temptask
};  

    index++

    tasks.sort(function(a,b){return new Date(b.Date).getTime() - new Date(a.Date).getTime()});

    var tablecode = "<table class = 'tasktable'  border='1'>" +
        "<tr>"+
        "<th>Date</th>"+
        "<th>Task</th>"+
        "</tr>";
    for (var i = 0; i < tasks.length; i++) {
        tablecode = tablecode + "<tr>" +
            "<td>" + tasks[i]["Date"] + " </td>" +
            "<td>" + tasks[i]["Task"] + " </td>" +
            "</tr>";
    }

    tablecode = tablecode + "</table>";

    document.getElementById("bottomright").innerHTML = tablecode;


return false;

}

Upvotes: 0

Views: 1362

Answers (1)

Henrik Nielsen
Henrik Nielsen

Reputation: 410

In your addTask function, you are declaring tempdate as a Date, but later converting it to a string by assigning string values to it. Try something like this instead:

var td = document.getElementById("taskdate").value;
var tempdate = new Date(td);

This sets tempdate as a Date, not a string. Then in your loop just call toDateString() on your Date, like so:

"<td>" + tasks[i]["Date"].toDateString() + " </td>"

Upvotes: 1

Related Questions