GOAL : 다양한 함수를 통해 MYSQL에서 날짜와 시간을 다룬다.

날짜, 시간 형식 지정 및 게산

형식, 포맷 지정하기

DATE_FORMAT 함수

DATE_FORMAT(date, type)

ex)
date = '2023-02-13 11:30:14'
type = '%Y/%m/%d'

# '2023/02/13'
  • date : 형식을 갖춘 날짜 및 시각
  • type : 반환받을 형식

 

자주 사용하는 형식

입력된 날짜의 형식을 'yy-mm-dd'와 같이 바꿉니다.

'2023-02-13 13:54:22' 같은 형식을 '2023-02-13'로 바꿀 때 사용합니다.

 

다양한 Format Description 확인

https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_date-format

 

MySQL :: MySQL 8.0 Reference Manual :: 12.7 Date and Time Functions

12.7 Date and Time Functions This section describes the functions that can be used to manipulate temporal values. See Section 11.2, “Date and Time Data Types”, for a description of the range of values each date and time type has and the valid formats

dev.mysql.com

 

두 날짜 사이 시간 계산하기

TIMESTAMP 함수

두 날짜 사이의 다양한 형식을 계산할 수 있는 함수입니다.

TIMESTAMP(type, start_time, end_time)

type : 반환받을 값의 형식

start_time : 시작 시각

end_time : 종료 시각

 

이 때 입력되는 형식은 'yy-mm-dd' 또는 'yy-dd-mm hh-mm-ss' 을 따릅니다.

반환받을 값은 아래아 같은 종류가 있습니다.

SECOND
MINUTE
HOUR 시간
DAY
WEEK
MONTH
YEAR

더 많은 파라미터 보기

MICROSECOND (microseconds), SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, or YEAR

https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_timestampadd

 

MySQL :: MySQL 8.0 Reference Manual :: 12.7 Date and Time Functions

12.7 Date and Time Functions This section describes the functions that can be used to manipulate temporal values. See Section 11.2, “Date and Time Data Types”, for a description of the range of values each date and time type has and the valid formats

dev.mysql.com

 

DATEDIFF 함수

두 날짜 사이의 일수를 계산합니다.

DATEDIFF(end_time, start_time)

 

  • end_time : 종료 시각
  • start_time : 시작 시각

이 때 입력되는 형식은 'yy-mm-dd' 또는 'yy-dd-mm hh-mm-ss' 을 따릅니다.

시간은 계산에서 제외되며 정해진 형식에 벗어난 경우 NULL을 반환합니다.

 

예를 들어, 다음과 같은 경우는 2월 33일은 없으므로 NULL을 반환합니다.

DATEDIFF('2023-02-13', '2023-02-12') # 1
DATEDIFF('2023-02-33', '2023-02-12') # NULL

 

TIMEDIFF 함수

두 날짜 사이의 시간을 계산합니다.

TIMEDIFF(end_time, start_time)
  • end_time : 종료 시각
  • start_time : 시작 시각

이 때 입력되는 형식은 'hh:mm:ss' 와 같은 시간 형식 또는 'yy-dd-mm hh-mm-ss' 을 따릅니다.

위와 마찬가지로 형식에 벗어난 값은 NULL을 반환합니다.

'개발일기 > Database' 카테고리의 다른 글

[DB] SQL 기본 문법  (0) 2022.04.22
[DB] 관계형 데이터베이스(RDBMS)? 주요 용어 정리  (0) 2022.04.14

+ Recent posts