1

I am building short web app, and using axios.js to send data to database. But when I am fetching date from database, complete date is rendered, whereas I want only getDate(), getMonth() and getFullYear() to be working, but they doesn't seem like working.

This is windows 7 localhost server. I already tired calling it in different ways.

function itemTemplate(item) {
  return `<li class="list-group-item list-group-item-action d-flex align-items-center justify-content-between" 
  style = "background-color: #cff0cc;
    color: #498a17;
    font-family: 'Kite One', sans-serif;">
  <span class="item-text">Date: ${item.date.getDate()} / ${item.date.getMonth() +
    1} / ${item.date.getFullyear()} - ${item.text}</span>
  <div>
  <button data-id="${
    item._id
  }" class="edit-me btn btn-primary btn-sm" style="background-color: darkgrey;border-color: grey;"><i class="fa fa-edit" style="width: 10px;"></i></button>
  <button data-id="${
    item._id
  }" class="delete-me btn btn-danger btn-sm"><i class="fa fa-minus-circle" aria-hidden="true" style="width: 10px;"></i>
  </button>
  </div>
  </li>`;
}

// Initial Page Load Render
let ourHTML = items
  .map(function(item) {
    return itemTemplate(item);
  })
  .join("");
document.getElementById("item-list").insertAdjacentHTML("beforeend", ourHTML);

// Create Feature
let createField = document.getElementById("create-field");
let createdDate = new Date();

document.getElementById("create-form").addEventListener("submit", function(e) {
  e.preventDefault();
  axios
    .post("/create-item", { text: createField.value, date: createdDate })
    .then(function(response) {
      // Create the HTML for a new item
      document
        .getElementById("item-list")
        .insertAdjacentHTML("beforeend", itemTemplate(response.data));
      createField.value = "";
      createField.focus();
    })
    .catch(function() {
      res.send("Please try again later.");
    });
});

Expected is, working of those three date functions, but error message shows up "item.date" is undefined at line 6

Suhem Bali
  • 52
  • 1
  • 8
  • what is `items` - it's not declared anywhere - it should be an array of objects that have `date`, `text` and `_id` properties, but it's not clear where it comes from – Jaromanda X Sep 12 '19 at 10:50
  • @JaromandaX `let ourHTML = items` here `items` is the collection name in my database. – Suhem Bali Sep 12 '19 at 10:53
  • yes, and what is the content of this variable? perhaps it's NOT what you think it is ... try debugging by `console.log(items)` just before that line, and see what it contains – Jaromanda X Sep 12 '19 at 10:54
  • @JaromandaX when I use `${item.date}` it is working well an good, complete date is rendered including timestamp and all. but when I add function to `${item.date}` to `${item.date.getDate()}` I get an error saying item.date is undefined – Suhem Bali Sep 12 '19 at 10:56
  • @JaromandaX as you said to `console.log(items)` I did it just right now, and it contains everything that I expect it to be there. – Suhem Bali Sep 12 '19 at 10:59
  • then EVERY `item` will have a `date` property, so the error won't happen ... but it does! that's mysterious - perhaps you're not reading the console output correctly ... would you post, in the question, at least part of the output you get from `console.log(items)` – Jaromanda X Sep 12 '19 at 11:09
  • `item.date` will not be a date object and `item.date.getYear()` will likely result in a "undefined is not a function" error. You will need to parse/convert these values in to Date objects `new Date(item.date)` before you can call any of these functions successfully – phuzi Sep 12 '19 at 12:28
  • Running `new Date(string)` without knowing the format of the string is risky @phuzi... – Heretic Monkey Sep 12 '19 at 12:44
  • 2
    Possible duplicate of [Why javascript getTime() is not a function?](https://stackoverflow.com/questions/2627650/why-javascript-gettime-is-not-a-function) – Heretic Monkey Sep 12 '19 at 12:47

1 Answers1

2

Try to use like this

${(new Date(item.date)).getDate()}

${(new Date(item.date)).getMonth()}

${(new Date(item.date)).getFullyear()}

item.date is a simple string and it has no method called getDate, getMonth or getFullyear. To access these methods you need a date object. So pass the item.date in a Date constructor, Then you will be able to access all those methods.

Mahmudur Rahman
  • 745
  • 5
  • 13
  • Would be helpful to explain why this works when the code in the question doesn't – phuzi Sep 12 '19 at 12:28
  • 1
    This could be very wrong, depending on the format of the date coming back from the service. For instance, if the date is coming back as "12/09/2019" it might be interpreted as 2019-12-09 or 2019-09-12, depending on the browser and the settings of the user. See [Why does Date.parse give incorrect results?](https://stackoverflow.com/q/2587345/215552). – Heretic Monkey Sep 12 '19 at 12:43
  • @PrisonerRaju Yes this code worked out for me. Thank you. – Suhem Bali Sep 13 '19 at 12:00