programmers

[JAVA] ☆ 2016년 - 날짜(Date, Calendar 등)

아잠만_ 2024. 7. 15. 16:50

문제 설명
2016년 1월 1일은 금요일입니다. 2016년 a월 b일은 무슨 요일일까요? 두 수 a ,b를 입력받아 2016년 a월 b일이 무슨 요일인지 리턴하는 함수, solution을 완성하세요. 요일의 이름은 일요일부터 토요일까지 각각 SUN,MON,TUE,WED,THU,FRI,SAT

입니다. 예를 들어 a=5, b=24라면 5월 24일은 화요일이므로 문자열 "TUE"를 반환하세요.

제한 조건
2016년은 윤년입니다.
2016년 a월 b일은 실제로 있는 날입니다. (13월 26일이나 2월 45일같은 날짜는 주어지지 않습니다)

풀이 - Date

import java.text.SimpleDateFormat;
import java.util.*;
class Solution {
    public String solution(int a, int b) {
        String[] arr = {"SUN","MON","TUE","WED","THU","FRI","SAT"};
        int idx = 0;
        try{
        SimpleDateFormat format = new SimpleDateFormat("yyyy.M.d");
        Date date = format.parse("2016."+a+"."+b);
        idx=date.getDay();
        } catch(Exception e){
            System.out.println(e.getMessage());
        }
        return arr[idx];
    }
}

풀이 2 - Calendar

import java.util.*;
class Solution {
    public String solution(int a, int b) {
    	Calendar cal = new Calendar.Builder().setCalendarType("iso8601")
                        .setDate(2016, a - 1, b).build();
        return cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, new Locale("ko-KR")).toUpperCase();
    }
}

풀이 3 - LocalDate

import java.time.*;
class Solution {
  public String solution(int a, int b) {
      return LocalDate.of(2016, a, b).getDayOfWeek().toString().substring(0,3);
  }
}

풀이 4 - 계산

class Solution {
  public String solution(int a, int b) {
      String answer = "";

      int[] c = {31,29,31,30,31,30,31,31,30,31,30,31}; // 마지막 일
      String[] MM ={"FRI","SAT","SUN","MON","TUE","WED","THU"}; 
      // 요일 (1월 1일이 금요일이므로 금요일부터 시작)
      int Adate = 0; 
      for(int i = 0 ; i< a-1; i++){
          Adate += c[i]; // 그 전달 일
      }
      Adate += b-1; // 오늘 일
      answer = MM[Adate %7];
      return answer;
  }
}