자바 요일구하기

2020. 9. 3. 18:46 Spring Framework/Spring boot

자바에서 요일(day of week)을 구하는 간단한 방법

(원문:http://www.leveluplunch.com/java/examples/get-day-of-week/)


Java Calendar

Calendar cal = Calendar.getInstance();

cal.set(Calendar.MONTH, Calendar.APRIL);

cal.set(Calendar.DAY_OF_MONTH, 4);

cal.set(Calendar.YEAR, 2016);

int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);

assertEquals(Calendar.FRIDAY, dayOfWeek);


Java 8

LocalDate date = LocalDate.of(2016, Month.APRIL, 4);

DayOfWeek dayOfWeek = date.getDayOfWeek();

assertEquals(DayOfWeek.FRIDAY, dayOfWeek);

또는 

int dayOfWeek2 = dayOfWeek.get(ChronoField.DAY_OF_WEEK);

assertEquals(DayOfWeek.FRIDAY.getValue(), dayOfWeek2);

또는    

LocalDateTime localDateTime = LocalDateTime.of(2016, Month.APRIL, 4, 5, 4);

DayOfWeek dayOfWeek3 = localDateTime.getDayOfWeek();

assertEquals(DayOfWeek.FRIDAY, dayOfWeek3);


Joda Time

DateTime dateTime = new DateTime(2016, 4, 4, 0, 0);

int dayOfWeek = dateTime.getDayOfWeek();

assertEquals(DateTimeConstants.FRIDAY, dayOfWeek);


Old JDK

int day = 2;
DateFormatSymbols dfs = DateFormatSymbols.getInstance(Locale.ENGLISH);
System.out.println(dfs.getWeekdays()[day % 7 + 1]);



출처: https://springboot.tistory.com/42?category=620230 [스프링부트는 사랑입니다]