공부한거 잊었을 때 보려고 만든 블로그

자바 스프링 기상청 단기예보 (동네날씨) API (1) 날짜와 시간 본문

자유 주제

자바 스프링 기상청 단기예보 (동네날씨) API (1) 날짜와 시간

Parcon 2023. 5. 2. 20:32

기상청에서 사용하는 위치 정보는 위도 경도가 아니라 격자 정보를 사용한다.

 

위도경도를 격자로 변환해주는 코드는 기상청에서 제공해주지만 c언어로 작성되어있다.

(https://www.data.go.kr/data/15084084/openapi.do 첨부파일)

 

사람들이 다른 언어로도 사용가능하게 공유하고 있다.

(https://gist.github.com/fronteer-kr/14d7f779d52a21ac2f16)

 

위도 경도를 격자 정보로 변환해주는 코드는 많지만 어디에도

base_date와 base_time을 쉽게 작성해주는 코드는 없음!

 

 

단순히 날짜와 시간을 넣으면 API가 반응하지 않을 수 있다.

왜냐하면 해당 시간에 발표된 날씨 정보가 없을 수 있기 때문이다.

Base_time : 0200, 0500, 0800, 1100, 1400, 1700, 2000, 2300 (1 8)

 

API 제공 시간(~이후) : 02:10, 05:10, 08:10, 11:10, 14:10, 17:10, 20:10, 23:10

(Base_time은 날씨 정보가 가지는 시간이지만 업데이트는 10분후에 된다) 

 

예를들어, 오전 8시 5분에 8시의 날씨를 알고 싶어서 0800을 요청하면 아직 업데이트가 되지않았기때문에 API가 반응하지 않는다.

8시 10분이 지나야 8시 정보를 알 수 있는 것이다.

 

또 오전 1시에 최근 날씨를 알고 싶으면 어제 23시 날씨 정보를 가져와야하기때문에 Base_date에 하루를 빼줘야한다.

이정도로 실시간 날씨를 알고 싶으면 초단기예보를 이용하는게 속편하다.

 

public String getDate(int minus)
{
    // 현재 날짜 가져오기
    LocalDate now = LocalDate.now().minusDays(minus);

    // DateTimeFormatter를 사용하여 날짜 포맷 변경
    String formattedDate = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));

    return formattedDate;
}

public String getTime()
{
    // 현재 시간 가져오기
    LocalDateTime now = LocalDateTime.now();

    // DateTimeFormatter를 사용하여 시간 포맷 변경
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHmm");
    String formattedTime = now.format(formatter);

    return convertTime(formattedTime);
}

public String convertTime(String inputTime) {
    int[] arr = {23, 20, 17, 14, 11, 8, 5, 2 ,-1};
    int inputHour = Integer.parseInt(inputTime.substring(0, 2));
    int inputMinute = Integer.parseInt(inputTime.substring(2));

	boolean refresh = false;

    if(inputMinute > 10) {
        refresh = true;
    }

    for (int i = 0; i < arr.length; i++) {
        if ((!refresh && arr[i] < inputHour) || (refresh && arr[i] <= inputHour)) {
            inputHour = arr[i];
            break;
        }
    }

    String convertedHourStr = String.format("%02d", inputHour);
    return convertedHourStr + "00";
}

 

 

base_date에 date를 인코딩하고

base_time에 now_time을 인코딩해서 API를 날리면 된다.