๐Ÿ“…๐Ÿ“… JS์—์„œ ๋‚ ์งœ๋ฅผ ๋น„๊ตํ•˜๋Š” ๋ฐฉ๋ฒ•(์ผ ์ฐจ์ด ๊ตฌํ•˜๊ธฐ)

3125 ๋‹จ์–ด webdevjavascriptbeginners
๋‚ ์งœ ๋ฌธ์ž์—ด๋กœ ์‹œ์ž‘ํ•˜๊ณ  ํ˜„์žฌ ๋‚ ์งœ๊นŒ์ง€์˜ ๋‚ ์งœ ์ฐจ์ด๋ฅผ ๊ณ„์‚ฐํ•˜๋ ค๊ณ  ํ•œ๋‹ค๊ณ  ๊ฐ€์ •ํ•ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.
  • ๋จผ์ € ๋ฌธ์ž์—ด์„ ๋‚ ์งœ๋กœ ๋ณ€ํ™˜ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค
  • .
  • ๊ทธ๋Ÿฌ๋ฉด ์˜ค๋Š˜ ๋‚ ์งœ
  • ๊ฐ€ ํ‘œ์‹œ๋ฉ๋‹ˆ๋‹ค.
  • ๋‘ ๊ฐœ
  • ๋น„๊ต

    ๊ทธ๋ ‡๋‹ค๋ฉด ๋ฌธ์ž์—ด์„ ๋‚ ์งœ๋กœ ์–ด๋–ป๊ฒŒ ๋ณ€ํ™˜ํ•ฉ๋‹ˆ๊นŒ? Date ์ƒ์„ฑ์ž๊ฐ€ ์ด ์ž‘์—…์„ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค. ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋ฌธ์ž์—ด์„ ์ „๋‹ฌํ•˜์‹ญ์‹œ์˜ค.

    const pastDate = new Date("2017-04-15")
    

    ๋นˆ ์ƒ์„ฑ์ž๋กœ ์–ป์„ ์ˆ˜ ์žˆ๋Š” ์˜ค๋Š˜ ๋‚ ์งœ:

    const today = new Date()
    

    ์ด์ œ ๋‘ ๋‚ ์งœ๋ฅผ ๋น„๊ตํ•ด ๋ด…์‹œ๋‹ค. ์ด๋ฅผ ์œ„ํ•ด UNIX ์‹œ๊ฐ„์„ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. UNIX ์‹œ๊ฐ„์€ 1970๋…„ 1์›” 1์ผ 00:00:00 ์ดํ›„ ๊ฒฝ๊ณผ๋œ ์‹œ๊ฐ„(๋ฐ€๋ฆฌ์ดˆ)์ž…๋‹ˆ๋‹ค.

    const pastDate = new Date("2017-04-15")
    const today = new Date()
    
    const differenceInMs = today.getTime() - pastDate.getTime()
    

    ์ด๊ฒƒ์€ ์šฐ๋ฆฌ์—๊ฒŒ ๋ฐ€๋ฆฌ์ดˆ ๋‹จ์œ„์˜ ์ฐจ์ด๋ฅผ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค. ์ด์ œ ๋‚ ์งœ๋กœ ๋ณ€ํ™˜ํ•ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. 1000์œผ๋กœ ๋‚˜๋ˆ„๋ฉด ๊ทธ ์ฐจ์ด๋ฅผ ์ดˆ ๋‹จ์œ„๋กœ ์•Œ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๊ฒƒ์„ 60์œผ๋กœ ๋‚˜๋ˆ„๋ฉด ๋ถ„์ด ๋ฉ๋‹ˆ๋‹ค. ๋˜ ๋‹ค๋ฅธ 60์€ ์šฐ๋ฆฌ์—๊ฒŒ ์‹œ๊ฐ„์„ ์ค๋‹ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๋˜ ๋‹ค๋ฅธ 24์ผ์€ ์šฐ๋ฆฌ์—๊ฒŒ ์ผ์„ ์ค๋‹ˆ๋‹ค.

    const pastDate = new Date("2017-04-15")
    const today = new Date()
    
    const differenceInMs = today.getTime() - pastDate.getTime()
    const differenceInDays = differenceInMs / 1000 / 60 / 60 / 24;
    

    ์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ