Updated:

Tags:

Categories:

📌 카운트 다운

let time = 125; //카운트다운 할 시간초

let timer = setInterval(function() {
    if(time >= 0){
        const min = String(Math.floor(time/60)).padStart(2,"0");
        const sec = String(time % 60).padStart(2,"0");
        console.log(`${min}:${sec}`);
        time--;
    } else {
        console.log('end');
        clearInterval(timer);
    }
},1000)

📌 로또(랜덤 숫자) 코드

function roll(){
    let result;
    let num = Math.random();
        
    result = Math.floor(num * 45 + 1);
    console.log(result);
}
/*
-설명-
로또는 1에서 45까지의 숫자가 존재하고(0은 없음), Math.random() 으로 1~45의 숫자가 나오게끔 코드를 작성해야한다.
Math.random()은 0초과~1미만의 숫자(ex: 0.00..1~0.99..9) 의 숫자가 나오는데,
이 숫자에 45를 곱하고 1을 더한 후 소숫점버림을 하면 된다.
*/

let a = 0.1
let b = 0.3
let c = 0.6
let d = 0.8

let e = 0.00000001 //Math.random() 의 임의 최소 숫자
let f = 0.9999999999 //Math.random() 의 임의 최대 숫자

console.log(a * 45) // 4.5
console.log(b * 45) // 13.5
console.log(c * 45) // 27
console.log(d * 45) // 36
console.log(e * 45) // 4.5000000000000003e-7
console.log(f * 45) // 44.9999999955

console.log(a * 45 + 1) // 5.5
console.log(b * 45 + 1) // 14.5
console.log(c * 45 + 1) // 28
console.log(d * 45 + 1) // 37
console.log(e * 45 + 1) // 1.00000045
console.log(f * 45 + 1) // 45.9999999955

console.log(Math.floor(a * 45 + 1)) // 5
console.log(Math.floor(b * 45 + 1)) // 14
console.log(Math.floor(c * 45 + 1)) // 28
console.log(Math.floor(d * 45 + 1)) // 37
console.log(Math.floor(e * 45 + 1)) // 1
console.log(Math.floor(f * 45 + 1)) // 45

📌 현재시간에서 n일 후 날짜 구하기 (?)

const getToday = (add = 0) => {
  const time = new Date();
  const UTC = time.getTime() + time.getTimezoneOffset() * 60 * 1000;
  const nineHours = 9 * 60 * 60 * 1000;

  const date = new Date(UTC + nineHours);
  date.setDate(date.getDate() + add);

  const yyyy = String(date.getFullYear());
  const mm = String(date.getMonth() + 1).padStart(2, '0');
  const dd = String(date.getDate()).padStart(2, '0');
  const h = String(date.getHours()).padStart(2, '0');
  const m = String(date.getMinutes()).padStart(2, '0');
  const s = String(date.getSeconds()).padStart(2, '0');
  const ms = String(date.getMilliseconds()).padStart(3, '0');

  return `${yyyy}-${mm}-${dd} ${h}:${m}:${s}:${ms}`;
};

이 부분은 여기를 참고해서 작성하였다. https://hianna.tistory.com/451
그런데 VScode 에서는 new Date() 를 선언할 시 크롬처럼 한국 시간을 알려주는게 아니라 (Sat Jul 02 2022 02:44:35 GMT+0900 (대한민국 표준시))
자꾸 ISO String 값 (2022-07-01T17:44:35.103Z) 을 준다.
분명히 const date = new Date(UTC + nineHours); 이렇게 시간을 더해줘도
아래 두개의 결과가 같다. 영문을 모르겠다. 시간을 계산한 값을 넣어서 다시 new Date() 를 선언해도 결과가 같다.

const time = new Date();
console.log(time) // 2022-07-01T17:49:48.884Z

const date = new Date(UTC + nineHours);
console.log(date) // 2022-07-01T17:49:48.884Z

아래 stackoverflow 글을 참고해보아야겠다.
https://stackoverflow.com/questions/57882972/vscode-javascript-get-exact-local-new-date-value
일단 VScode 에서의 표시 문제는 넘어가도록 하고.. date로 원하는 시간대를 구할 수 있다는 것을 배우게 되었다.

Leave a comment