● 首先我们将下面图片上的时间更换成现在的时间
const now = new Date();
const day = now.getDate();
const month = now.getMonth() + 1;
const year = now.getFullYear();
const hour = now.getHours();
const min = now.getMinutes();labelDate.textContent = `${day}/${month}/${year}, ${hour}:${min}`;
● 但是一般情况下,我们更喜欢能看到04/05这样的表达方式
const now = new Date();
const day = `${now.getDate()}`.padStart(2, 0);
const month = `${now.getMonth() + 1}`.padStart(2, 0);
const year = now.getFullYear();
const hour = `${now.getHours()}`.padStart(2, 0);
const min = `${now.getMinutes()}`.padStart(2, 0);labelDate.textContent = `${day}/${month}/${year}, ${hour}:${min}`;
注:padStart后面有两个参数,第一个参数就是必须为几位数,不够的用第二个参数补齐;
存取款时间
movs.forEach(function (mov, i) {const type = mov > 0 ? 'deposit' : 'withdrawal';const date = new Date(acc.movementsDates[i]);const day = `${date.getDate()}`.padStart(2, 0);const month = `${date.getMonth() + 1}`.padStart(2, 0);const year = date.getFullYear();const displayDate = `${day}/${month}/${year}`;const html = `<div class="movements__row"><div class="movements__type movements__type--${type}">${i + 1} ${type}</div><div class="movements__date">${displayDate}</div><div class="movements__value">${mov.toFixed(2)}€</div></div>`;containerMovements.insertAdjacentHTML('afterbegin', html);});
};
//
这段代码是一个循环,用于遍历movs数组中的每个元素,并根据元素的正负值确定交易类型(存款或取款)。然后,它创建一个表示交易日期的Date对象,并使用该对象来获取日期、月份和年份,并格式化为“dd/mm/yyyy”的形式。接下来,它根据交易类型、日期和交易金额,生成HTML代码,并将其插入到指定的容器元素中。
● 但是我们在申请贷款的时候会发现,时间并没有进行更新
这是因为我们的数组中仅仅定义了八个时间,当增加了一个我们无法读取到
● 很简单,我们只需要在每次转账或者贷款的时候添加一下此时的时间就可以了
//转账
if (amount > 0 &&receiverAcc &¤tAccount.balance >= amount &&receiverAcc?.username !== currentAccount.username) {// Doing the transfercurrentAccount.movements.push(-amount);receiverAcc.movements.push(amount);currentAccount.movementsDates.push(new Date().toISOString());receiverAcc.movementsDates.push(new Date().toISOString());// Update UIupdateUI(currentAccount);}
});
//贷款
btnLoan.addEventListener('click', function (e) {e.preventDefault();const amount = Math.floor(inputLoanAmount.value);if (amount > 0 && currentAccount.movements.some(mov => mov >= amount * 0.1)) {// Add movementcurrentAccount.movements.push(amount);currentAccount.movementsDates.push(new Date().toISOString());// Update UIupdateUI(currentAccount);}inputLoanAmount.value = '';
});