我有以下函数创建一个表并插入日期&在表内的行中添加价格:
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;
}
日期格式目前是:YYYY/MM/DD,我希望它是DD/MM/YYYY。我有下面的函数,重新格式化日期,因为我想要它,但我一直在努力实现到我的代码,因为我不能在innerHtml
中调用函数,其中日期被填充(item_date_created
)。有人能给点建议吗?
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"
}
例如,添加:
let reformattedDate = reformatDate(item.date_created);
forEach的给出如下输出:undefined/undefined/22/11/06
解决方法如下:
.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;
}