๐Ÿ”ฅ TIL - Day 38 - 2

Kim Dae Hyunยท2021๋…„ 10์›” 26์ผ
0

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
46/93

๐Ÿ“Œ Java ๋‚ ์งœ/์‹œ๊ฐ„ ๋‹ค๋ฃจ๊ธฐ

java.time ํŒจํ‚ค์ง€

  • LocalDate
  • LocalTime
  • LocalDateTime

๐Ÿ“Œ ๋‚ ์งœ/์‹œ๊ฐ„ ๋งŒ๋“ค๊ธฐ

// ์˜ค๋Š˜๋‚ ์งœ / ์‹œ๊ฐ„ / ๋‚ ์งœ ๋ฐ ์‹œ๊ฐ„
LocalDate nowDate = LocalDate.now()
LocalTime nowTime = LocalTime.now()
LocalDateTime nowDateTime = LocalDateTime.now();

// ๋‚ ์งœ ์ง์ ‘ ์ง€์ •
LocalDate date = LocalDate.of(2021, 10, 26);

๐Ÿ“Œ ๋‚ ์งœ ํ˜•์‹ ํฌ๋งทํŒ…

DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy/MM/dd");
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy๋…„ MM์›” dd์ผ");


String nowDate1 = formatter1.format(LocalDate.now());

String nowDate2 = formatter2.format(LocalDate.now());


System.out.println("nowDate1 = " + nowDate1);
System.out.println("nowDate2 = " + nowDate2);

๐Ÿ“Œ ๋‚ ์งœ ์‚ฌ์ด ๊ธฐ๊ฐ„ ๋‹ค๋ฃจ๊ธฐ (Period)

์ง์ ‘์ ์ธ ์—ฐ์‚ฐ์ด ์•„๋‹ˆ๊ณ  ๋ฉ”์„œ๋“œ๋ฅผ ์ด์šฉํ•˜๋‹ˆ ๊ต‰์žฅํžˆ ๋ช…์‹œ์ ์ด์–ด์„œ ์‹ค์ˆ˜? ์˜ ์—ฌ์ง€๊ฐ€ ์—†์„ ๊ฒƒ ๊ฐ™๋‹ค. ํด๋ž˜์Šค ์ด๋ฆ„์ •๋„๋Š” ๊ธฐ์–ตํ•˜๊ณ  ์• ์šฉํ•ด๋ณด์ž ใ…Ž

// 2021/10/26
LocalDate now = LocalDate.now();
LocalDate pastDate = LocalDate.of(2021,1,1);

// Period period = Period.between(์‹œ์ž‘๋‚ ์งœ, ๋๋‚ ์งœ);
Period period = Period.between(pastDate, now);

// pastDate๋กœ๋ถ€ํ„ฐ now๊ฐ€ ์–ผ๋งˆ๋‚˜ ์ง€๋‚ฌ๋Š”์ง€ ํ™•์ธ
System.out.println(period.getMonths()); // ๋ช‡ ๋‹ฌ์ด ์ง€๋‚ฌ๋Š”์ง€
System.out.println(period.getDays()); // ๋ช‡ ์ผ์ด ์ง€๋‚ฌ๋Š”์ง€

๐Ÿ“Œ ๋‘ ๋‚ ์งœ ๋น„๊ตํ•˜๊ธฐ

  • java.time ํŒจํ‚ค์ง€๋ฅผ ์ด์šฉํ•ด์„œ ๋งŒ๋“  ๋‚ ์งœ/์‹œ๊ฐ„ ๊ฐ์ฒด๋Š” ๋ถ€๋“ฑํ˜ธ๋ฅผ ์ด์šฉํ•œ ๋Œ€์†Œ ๋น„๊ต๊ฐ€ ์•ˆ ๋จ.
  • isAfter, isEqual, isBefore ๋ฉ”์„œ๋“œ ์ง€์›
// 2021/10/26
LocalDate now = LocalDate.now();
LocalDate pastDate = LocalDate.of(2021,1,1);

// ์ด๊ฑฐ๋Š” True - now๊ฐ€ pastDate ์ดํ›„์ธ์ง€
now.isAfter(pastDate);

// ์ด๊ฑฐ๋Š” False - now๊ฐ€ pastDate ์ด์ „์ธ์ง€
now.isBefore(pastDate);
profile
์ข€ ๋” ์ฒœ์ฒœํžˆ ๊นŒ๋จน๊ธฐ ์œ„ํ•ด ๊ธฐ๋กํ•ฉ๋‹ˆ๋‹ค. ๐Ÿง

0๊ฐœ์˜ ๋Œ“๊ธ€