[JS] Operations with Dates, Intl, setTimeout, setInterval
9715 ワード
コースソース:完全JavaScript Course 2022 Jonas(Udemy)
Creating Dates
new Date()
Operations With Dates
Intl.DateTimeFormat
Int.DataTimeFormatでlocale文字列を渡します.
ex)ja-JP,en-UK詳細はiso言語code table-Langosを検索してください!
Intl.NumberFormat
setTimeout
Creating Dates
new Date()
const now = new Date();
console.log(now);
//Tue Dec 21 2021 14:39:36 GMT+0900 (한국 표준시)
console.log(new Date('Tue Dec 21 2021 14:39:07'));
//Tue Dec 21 2021 14:39:07 GMT+0900 (한국 표준시)
console.log(new Date('December 24, 2015'));
//Thu Dec 24 2015 00:00:00 GMT+0900 (한국 표준시)
console.log(new Date(account1.movementsDates[0]));
//Tue Nov 19 2019 06:31:17 GMT+0900 (한국 표준시)
console.log(new Date(2037, 10, 19, 15, 23, 5));
//Thu Nov 19 2037 15:23:05 GMT+0900 (한국 표준시)
// 10 -> Nov Month in JS is 0 based.
console.log(new Date(2037, 10, 33));
//Thu Dec 03 2037 00:00:00 GMT+0900 (한국 표준시)
//자동으로 다음달로 넘어가줌.
console.log(new Date(0));
//Thu Jan 01 1970 09:00:00 GMT+0900 (한국 표준시)
console.log(new Date(3 * 24 * 60 * 60 * 1000));
//Sun Jan 04 1970 09:00:00 GMT+0900 (한국 표준시)
// 3일 뒤 => 3일 * 24시간 * 60분 * 60초 * 1000(milli secon로 바꾸기)
//3 * 24 * 60 * 60 * 1000 = 259200000 이 숫자를 1970년 1월1일로부터의 3일 뒤의 timestamp라고 부른다.
Working with datesconst future = new Date(2037, 10, 19, 15, 23);
console.log(future);
console.log(future.getFullYear()); //2037 주의) getYear()이 아닌 getFullYear()이용할 것!
console.log(future.getMonth()); //10
console.log(future.getDate()); //19
console.log(future.getDay()); //4
console.log(future.getHours()); //15
console.log(future.getMinutes()); //23
console.log(future.getSeconds()); //0
console.log(future.toISOString());
//2037-11-19T06:23:00.000Z
console.log(future.getTime()); //2142224580000 1970년 1월1일로부터의 timestamp
console.log(new Date(2142224580000)); //Thu Nov 19 2037 15:23:00 GMT+0900 (한국 표준시)
console.log(Date.now()); //1640066023880 지금 당장의 timestamp를 제공한다.
future.setFullYear(2040);
console.log(future); //Mon Nov 19 2040 15:23:00 GMT+0900 (한국 표준시)
ex)const formatMovementDate = function(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, movements, sort = false) {
const movs = sort
? acc.movements.slice().sort((a, b) => a - b)
: acc.movements;
movs.forEach(function (mov, i) {
const date = new Date(acc.movementsDates[i]);
const displayDate = formatMovementDate(date);
const html = `<div class="movements__date">${displayDate}</div>
`;
containerMovements.insertAdjacentHTML('afterbegin', html);
});
};
注意すべきはpadStartは文字列の後ろにしか書けないのでtemplate literalなどの文字列タグを使用してください!Operations With Dates
const future = new Date(2037, 10, 19, 15, 23);
console.log(+future); //2142224580000
console.log(future); //Thu Nov 19 2037 15:23:00 GMT+0900 (한국 표준시
const calcDaysPassed = (date1, date2) =>
Math.abs(date2 - date1) / (1000 * 60 * 60 * 24);
const days1 = calcDaysPassed(new Date(2037, 3, 4), new Date(2037, 3, 14));
console.log(days1); //10 (days)
ex)const formatMovementDate = function (date){
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`; }
Internationalizing Dates (Intl)Intl.DateTimeFormat
Int.DataTimeFormatでlocale文字列を渡します.
ex)ja-JP,en-UK詳細はiso言語code table-Langosを検索してください!
const now = new Date();
const options = {
hour: 'numeric',
minute: 'numeric',
day: 'numeric',
month: 'long',
year: 'numeric',
weekday: 'short',
};
const locale = navigator.language;
console.log(locale); //ko-KR
labelDate.textContent = new Intl.DateTimeFormat(locale, options).format(now);
Internationalizing Numbers (Intl)Intl.NumberFormat
const num = 345235435.23;
const options = {
style: 'currency', // ex) 'percent' 'decimal'
//unit: 'mile-per-hour', //ex) 'celsius',
currency: 'EUR',
//useGrouping: false,
};
console.log('US :', new Intl.NumberFormat('en-US', options).format(num));
// US : €345,235,435.23
console.log('Germany :', new Intl.NumberFormat('de-DE', options).format(num));
//Germany : 345.235.435,23 €
console.log('Syria :', new Intl.NumberFormat('ar-SY', options).format(num));
//Syria : ٣٤٥٬٢٣٥٬٤٣٥٫٢٣ €
console.log('Korea :', new Intl.NumberFormat('ko-KR', options).format(num));
//Korea : €345,235,435.23
console.log(
navigator.language,
new Intl.NumberFormat(navigator.language, options).format(num)
);
//ko-KR €345,235,435.23
ex)const formatMovementDate = function (date, locale) {
return new Intl.DateTimeFormat(locale).format(date);}
const formatCur = function (value, locale, currency) {
return new Intl.NumberFormat(locale, {
style: 'currency',
currency: currency,
}).format(value);
};
const displayMovements = function (acc, movements, sort = false) {
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 formattedMov = formatCur(mov, acc.locale, acc.currency);
const html = `<div class="movements__date">${displayDate}</div>
<div class="movements__value">${formattedMov}</div>
</div>
`;
containerMovements.insertAdjacentHTML('afterbegin', html);
});
};
btnLogin.addEventListener('click', function (e) {
// Create Current Date and Time
const now = new Date();
const options = {
hour: 'numeric',
minute: 'numeric',
day: 'numeric',
month: 'numeric',
year: 'numeric',
//weekday: 'short',
};
labelDate.textContent = new Intl.DateTimeFormat(
currentAccount.locale,
options
).format(now);}
Timers: setTimeout and setIntervalsetTimeout
const ingredients = ['olives', 'spinach'];
const pizzaTimer = setTimeout(
(ing1, ing2) => console.log(`Here is your pizza with ${ing1} and ${ing2}`),
3000,
...ingredients
);
console.log('Waiting...');
//Waiting
//Here is your pizza with olives and spinach
// setTimout의 세번째 인자 값들이 setTimeout callback함수의 매개변수 값임...!
if (ingredients.includes('spinach')) clearTimeout(pizzaTimer);
//pizzaTimer is not working
setInterval setInterval(function () {
const now = new Date();
console.log(now);
}, 1000);
Implementing a Countdown Timerlet timer;
const startLogOutTimer = function () {
const tick = function () {
const min = `${Math.floor(time / 60)}`.padStart(2, 0);
const second = `${time % 60}`.padStart(2, 0);
// In each call, print the remaining time to UI
labelTimer.textContent = `${min}:${second}`;
// When 0 seconds, stop timer and log out user
if (time === 0) {
clearInterval(timer);
labelWelcome.textContent = `Log in to get started`;
containerApp.style.opacity = 0;
}
// Decrease 1S
time--;
};
// Set time to 5 minutes
let time = 120;
// Call the timer every seconds
tick();
const timer = setInterval(tick, 1000);
return timer;
};
btnLogin.addEventListener('click', function (e) {
if (timer) clearInterval(timer); // 두 timer가 중복되어 작동하지 않도록!
timer = startLogOutTimer(); })
btnTransfer.addEventListener('click', function (e) {
// Reset Timer
clearInterval(timer);
timer = startLogOutTimer();}
Reference
この問題について([JS] Operations with Dates, Intl, setTimeout, setInterval), 我々は、より多くの情報をここで見つけました https://velog.io/@hoje15v/Today-I-Learned-Operations-with-Dates-Intl-setTimeout-setIntervalテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol