我们可以使用国际化API自动的格式化数字或者日期,并且格式化日期或数字的时候是按照各个国家的习惯来进行格式化的,非常的简单;
const now = new Date();
labelDate.textContent = new Intl.DateTimeFormat('zh-CN').format(now);
比如说这是按照中国的习惯来进行格式化,我们习惯按照年月日时分秒来排列时间
● 但是这样格式化的话只能出现年月日,时间却没有了
const now = new Date();
const options = {hour: 'numeric',minute: 'numeric',day: 'numeric',month: 'numeric',year: 'numeric',weekday: 'long',
};
labelDate.textContent = new Intl.DateTimeFormat('zh-CN', options).format(now);
● 我们也可以直在浏览器中自动的获取你的地区,无需手动的去指定地区
const now = new Date();
const options = {hour: 'numeric',minute: 'numeric',day: 'numeric',month: 'numeric',year: 'numeric',weekday: 'long',
};const lacale = navigator.language;
console.log(lacale);labelDate.textContent = new Intl.DateTimeFormat(lacale, options).format(now);
● 再次回到我们的应用程序,我们给每个用户中定义了国家码,要实现每个人登录按照他国家的习惯来显示时间
const now = new Date();
const options = {hour: 'numeric',minute: 'numeric',day: 'numeric',month: 'numeric',year: 'numeric',
};
labelDate.textContent = new Intl.DateTimeFormat(currentAccount.locale,options
).format(now);
● 除了这些,存取款的时间也需要根据用户国家改变
const formatMovementDate = function (date, locale) {const calcDaysPassed = (date1, date2) =>Math.round(Math.abs(date2 - date1) / (1000 * 60 * 60 * 24));const daysPassed = calcDaysPassed(new Date(), date);if (daysPassed === 0) return '今天';if (daysPassed === 1) return '昨天';if (daysPassed <= 7) return `${daysPassed} 天前`;return new Intl.DateTimeFormat(locale).format(date);// const day = `${date.getDate()}`.padStart(2, 0);// const month = `${date.getMonth() + 1}`.padStart(2, 0);// const year = date.getFullYear();// return `${day}/${month}/${year}`;
};const displayMovements = function (acc, sort = false) {containerMovements.innerHTML = '';const movs = sort? acc.movements.slice().sort((a, b) => a - b): acc.movements;movs.forEach(function (mov, i) {const type = mov > 0 ? 'deposit' : 'withdrawal';const date = new Date(acc.movementsDates[i]);const displayDate = formatMovementDate(date, acc.locale);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);});
};
大家也可以根据下面的文档详细的学习这个国际化API
INIT