0

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;

}
1
  • If you can parse the dates when sorting, surely you can parse the dates when outputting as well, and just keep an array of the seven days and twelve months, and this stuff is easy-peasy Commented Dec 6, 2015 at 0:15

1 Answer 1

1

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>"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.