0

I have a homework of Javascript exercise that goes like this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Producst</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body dir="rtl">
    <main id="root"></main>
    <button class="btn" id="changeProducts">Make Changes</button>

    <script src="script.js"></script>
  </body>
</html>

Here we have 5 products that are getting written at <main id="root"></main> like this:

enter image description here

And this content comes from the script.js which holds:

const main = document.getElementById('root');

function renderProducts(products) {
  main.innerHTML = products
    .map(
      product => `<div class="product" data-product-id="${product.id}">
                    <h1>${product.title}</h1>
                    <p class="price">${product.price} Toman</p>
                    <p class="date">${product.date}</p>
                  </div>`
    )
    .join('');
}

const products = [
  {
    id: 1,
    title: 'Product 1',
    price: '32000',
    date: '1596902113'
  },
  {
    id: 2,
    title: 'Product 2',
    price: '46000',
    date: '1555891200'
  },
  {
    id: 3,
    title: 'Product 3',
    price: '20000',
    date: '1515369600'
  },
  {
    id: 4,
    title: 'Product 4',
    price: '88000',
    date: '1509580800'
  },
  {
    id: 5,
    title: 'Product 5',
    price: '11000',
    date: '1477267200'
  }
];

renderProducts(products);

document
  .getElementById('changeProducts')
  .addEventListener('click', changeProducts);

function changeProducts() {
    main.innerHTML = products
    .map(
      product => `<div class="product" data-product-id="${product.id}">
                    <h1>${product.title}</h1>
                    <p class="price">${product.price / 2} تومان</p>
                    <p class="date">${product.date}</p>
                  </div>`
    )
    .join('');
}

So after user clicks on Make Changes button, the function changeProducts() will run and it will basically subtract the number by half and also should convert the product.date to localDateString.

So I know for converting, the code here is useful, but I don't know how to call the code inside changeProducts function!!

So if you know, please let me know, thanks!

Joe Davis
  • 13
  • 1

1 Answers1

0

Just change product.date to new Date(product.date * 1000).toLocaleDateString()

function changeProducts() {
    main.innerHTML = products
    .map(
      product => `<div class="product" data-product-id="${product.id}">
                    <h1>${product.title}</h1>
                    <p class="price">${product.price / 2} تومان</p>
                    <p class="date">${new Date(product.date * 1000).toLocaleDateString()}</p>
                  </div>`
    )
    .join('');
}
Jordy
  • 1,802
  • 2
  • 6
  • 25