웹개발/혼자하는 개발 공부

[자바스크립트] Numbers / Dates / Intl / Timers

데브리 2021. 9. 16. 11:23

 

convertion

console.log(Number('7'); // 7 
console.log(+'7'); // 7

parsing

console.log(Number.parseInt('20px')); // 20 
console.log(Number.parseInt('e13')); // NaN 
console.log(Number.parseInt(' 4.5rem ')); // 4 
console.log(Number.parseFloat(' 6.5rem ')); // 6.5

 

 

.isNaN

.isFinite

determines whether the passed value is a finite number(유한수)

(best way to check if the value is number)

console.log(Number.isNaN(10)); // false 
console.log(Number.isFinite(10); // true

 

 

Math and Rounding

console.log(Math,sqrt(25)); // 5 square root 
console.log(Math.max(5, 18, 23, 11, 2) // 23 
console.log(Math.PI * Number.parseFloat('10px') ** 2); // 314.159265... 
console.log(Math.trunc(Math.random() * 6) + 1); 
// math.ramdom generates a random number between 0 and 1


// Math.trunc 
console.log(Math.trunc(23.3)); // 23 
console.log(Math.round(-23.3)); // 23

// Math.round 
console.log(Math.round(23.3)); // 23 
console.log(Math.round(23.9)); // 24 

// Math.ceil: always round up 
console.log(Math.ceil(23.3)); // 24 
console.log(Math.ceil(23.9)); // 24 

// Math.floor: always round down 
console.log(Math.round(23.3)); // 23 
console.log(Math.round(23.9)); // 23 
console.log(Math.round(-23.3)); // 24 

// Rounding decimals 
console.log((2.7).toFixed(0)); // 3 <-string 
console.log((2.7).toFixed(3)); // 2.700 <-string 
console.log(+(2.345).toFixed(2)); // 2.35 <-number

 

 

 

 

.toFixed

금액에 . 표시할 때 쓰기!

Remainder Operator

returns the remainder of a division

console.log(5 % 2); // 1 5를 2로 나눈 후 남은 1을 return

often used to check whether a certain number is even or odd

 

BigInt (ES2000)

provides a way to represent whole numbers larger than 253 - 1, which is the largest number JavaScript can reliably represent. We can store numbers as large as we want.

console.log(123456789101112131415); // 123456789101112130000 
console.log(123456789101112131415n); // 123456789101112131415n 
console.log(BigInt(123456789101112131415n)); // 123456789101112131584n

Dates

 

 

dd/mm/yyyy 순으로 현재 시간 표시하기

const now = new Date(); 

const day = `${now.getDate()}`.padStart(2, 0); 
// 한자리 숫자일 때 앞에 0을 붙여 두자리 숫자로 표시함 

const month =`${now.getMonth() + 1}`.padStart(2, 0); 
// '+1'? because getMonth is 0 based 

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}`; 
// day/month/year, hour:mins

날짜 차이 계산하는 법

const future = new Date(2037, 10, 19, 15, 23); 
console.log(+future); // 2142274980000 

const calcDaysPassed = (date1, date2) => Math.abs(date2 - date1) / (1000 * 60 * 60 * 24); 
// 1000 million seconds * 60 seconds * 60 mins * 24 hrs 

const days1 = calcDaysPassed(new Date(2037, 3, 4), new Date(2037, 3, 14)); 
console.log(days1); // 10

날짜 차이 계산을 통해 today, yesterday,... days ago 만드는 법.

(인스타그램이나 페이스북 포스팅 시간처럼)

 

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`; 
    else {
      const day = `${date.getDate()}`.padStart(2, 0); 
      const month = `${date.getMonth() + 1}`.padStart(2, 0); 
      const year = date.getFullYear(); 
      return `${day}/${month}/${year}`; 
    }
};

Internationalizing Dates (Intl)*

Internationalization API. mdn

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl

 

Intl - JavaScript | MDN

The Intl object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting. The Intl object provides access to several constructors as well as functiona

developer.mozilla.org

 

 

 

const now = new Date(); 
labelDate.textContent = new Intl.DateTimeFormat('en-US').format(now); 
// iso language code table 참고할 것

 

위의 format에 추가로 시간을 넣을 때

numeric, long 수정 가능

 

const now = new Date(); 
const options = { 
  hour: 'numeric', 
  minute: 'numeric', 
  day: 'numeric', 
  month: 'long', 
  year: 'numeric', 
  weekday: 'long', 
}; 

labelDate.textContent = new Intl.DateTimeFormat('en-US', options).format(now); 

// localize dates 
'en-US' 대신 locale을 쓰면 user가 접속한 곳의 시간 날짜 format 으로 표시됨.

unit, percent, currency format

const num = 123456.78; 

const options = {
  style: 'currency', 
  unit: 'celsius', 
  currency: 'KRW',
}; 

console.log('US: ', new Intl.NumberFormat('en-US').format(num)); 
console.log('Spain: ', new Intl.NumberFormat('es-ES').format(num)); 
console.log('Korea: ', new Intl.NumberFormat('ko-KR').format(num)); 
console.log('Japan: ', new Intl.NumberFormat('ja-JP').format(num)); 

console.log(
  navigator.language, 
  new Intl.NumberFormat(navigator.language, options).format(num)
);

Timers

setTimeout()

Execute a specified block of code once after a specified time has elapsed

setTimeout( ,3000) // start counting after 3 seconds

setInterval

keeps running until we stop

setInterval(function () {
  const now = new Date(); 
  console.log(now); 
}, 1000); 
// executes 'now' every second

로그인하고 나서 일정 시간 후 자동 로그아웃되는 Timer 만드는 법

const startLogOutTimer = function () {
  const tick = function() {
    const min = String(Math.trunc(time / 60)).padStart(2, 0); 
    const sec = String(time % 60).padStart(2, 0); 
    
    // In each call, print the remaining time to UI 
    labelTimer.textContent = `${min}:${sec}`; 
    
    // When 0 second, stop timer and log out user
    if (time === 0) {
      clearInterval(timer); 
      labelWelcome.textContent = 'Log in to get started';
    }
    
      // Decrease is 
      time--; 
    
      // Set time 
      let time = 120; 
      
      // Start the timer right after we log in
      tick(); 
      const timer = setInterval(tick, 1000);
      
      // When 0 seconds, stop timer and log out user
  }, 1000);
}; 




// user가 로그아웃 하면 타이머도 멈추고, 새로운 user가 새로 로그인하면 새로 타이머가 시작되도록 리셋 
if(timer) clearInterval(timer); 
timer = startLogOutTimer(); 



// Reset timer user로 부터 어떤 activity가 있을 때 타이머가 다시 시작되도록 리셋 
clearInterval(timer); 
timer = startLogOutTimer();