[sql] 특정 날짜와 시간을 가장 가까운 다음 시간으로 조정하는 함수

먼저 다음과 같은 SQL 함수를 작성할 수 있습니다.

CREATE OR REPLACE FUNCTION round_up_time(input_time TIMESTAMP)
RETURNS TIMESTAMP AS
$$
DECLARE
    next_hour TIMESTAMP;
    next_day TIMESTAMP;
BEGIN
    next_hour := input_time + '1 hour'::interval;
    next_day := date_trunc('day', input_time) + '1 day';
    
    RETURN CASE 
        WHEN next_hour > next_day THEN next_day
        ELSE next_hour
    END;
END;
$$
LANGUAGE plpgsql;

위 함수는 입력된 시간에서 1시간을 더한 next_hour와 다음 날 00시로 조정한 next_day를 비교하여, 더 이른 시간을 반환합니다.

이제 함수를 호출해보겠습니다.

SELECT round_up_time('2023-07-15 14:40:00');

이 코드를 실행하면 2023년 7월 15일 15시가 출력됩니다.

참고문헌:

  1. PostgreSQL 공식문서. “PL/pgSQL - SQL Procedural Language.” https://www.postgresql.org/docs/current/plpgsql.html