I have the following function that creates a table and inserts the date & price into rows within the table:
function createTable({ data, propertyId }) {
const table = createElement({
tag: 'table',
id: `p-${propertyId}`,
border: '1',
});
const tableHeader = createElement({
tag: 'caption',
innerText: 'Table title',
});
const tableBody = createElement({
tag: 'tbody',
});
//order dates so that most recent is displayed last
data
.sort((prev, current) => {
const prevDate = prev['date_created'].replace('/', '-').replace('/', '-');
const currentDate = current['date_created']
.replace('/', '-')
.replace('/', '-');
return new Date(prevDate) - new Date(currentDate);
})
.forEach((item) => {
const row = createElement({
tag: 'tr',
});
const date = createElement({
tag: 'td',
innerHTML: item.date_created,
});
const price = createElement({
tag: 'td',
innerHTML: item.price,
});
row.append(date, price);
tableBody.append(row);
});
table.append(tableHeader, tableBody);
return table;
}
The date format is currently: YYYY/MM/DD and I'd like it to be DD/MM/YYYY. I have the below function that reformats the date as I'd like it to, but I've been struggling to implement into my code, as I can't call the function in innerHtml
where the date is being populated (item_date_created
). Can anyone please advise?
function reformatDate(dateStr) {
var dArr = dateStr.split('-'); // ex input: "2010-01-18"
return dArr[2] '/' dArr[1] '/' dArr[0].substring(2); //ex output: "18/01/10"
}
For example, adding:
let reformattedDate = reformatDate(item.date_created);
below for the forEach gives the following output:
undefined/undefined/22/11/06
CodePudding user response:
Managed to resolve the issue like so:
.forEach((item) => {
let reformattedDate = reformatDate(item.date_created);
const row = createElement({
tag: 'tr',
});
const date = createElement({
tag: 'td',
innerHTML: reformattedDate,
});
const price = createElement({
tag: 'td',
innerHTML: item.price,
className: 'pp-price',
});
row.append(date, price);
tableBody.append(row);
});
function reformatDate(dateStr) {
const [year, month, day] = dateStr.split('/');
const result = [day, month, year].join('/');
return result;
}