[JavaScript] Numbers, Dates, Intl, and Timers - Internationalizing Dates (Intl)
![[JavaScript] Numbers, Dates, Intl, and Timers - Internationalizing Dates (Intl)](https://cdn.hashnode.com/res/hashnode/image/unsplash/mZnx9429i94/upload/v1658167410185/n_yixikGo.jpeg)
const account1 = {
owner: 'Jonas Schmedtmann',
movements: [200, 455.23, -306.5, 25000, -642.21, -133.9, 79.97, 1300],
interestRate: 1.2, // %
pin: 1111,
movementsDates: [
'2019-11-18T21:31:17.178Z',
'2019-12-23T07:42:02.383Z',
'2020-01-28T09:15:04.904Z',
'2020-04-01T10:17:24.185Z',
'2020-05-08T14:11:59.604Z',
'2022-07-11T17:01:17.194Z',
'2022-07-14T23:36:17.929Z',
'2022-07-17T10:51:36.790Z',
],
currency: 'EUR',
locale: 'pt-PT', // de-DE
};
// Create current date and time after log in
const now = new Date();
const options = {
hour: 'numeric',
minute: 'numeric',
day: 'numeric',
month: 'numeric', // also available 'long' or '2-digit'. Those display another format of month. ex) 3, 03 for march.
year: 'numeric', // also available '2-digit'
// weekday: 'numeric', // available 'short', 'numeric', 'long'...
};
// const locale = navigator.language; // for automated update by user's browser
// console.log(locale);
labelDate.textContent = new Intl.DateTimeFormat(
currentAccount.locale,
options
).format(now); // ('Language-Country'), 'en-US' - USA, 'en-GB' - England, 'ko-KR' - Korea...
// Display Movements with Internationalized time
const formatMovementsDates = 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 'Today';
if (daysPassed === 1) return 'Yesterday';
if (daysPassed <= 7) return `${daysPassed} days ago`;
else {
// const month = `${date.getMonth() + 1}`.padStart(2, 0);
// const day = `${date.getDate()}`.padStart(2, 0);
// const year = date.getFullYear();
// return `${month}/${day}/${year}`;
return new Intl.DateTimeFormat(locale).format(date);
}
};
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 = formatMovementsDates(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);
});
};
US
England
Korea
Syria