MySQL

[MySQL] 날짜, 시간 처리

건휘맨 2024. 5. 16. 10:20
-- 년월일에서 날짜만 가져올때
select name, day(birthdate)
from people;

-- 월만 가져올때
select name, month(birthdate)
from people;

-- 년도만 가져올때
select name, year(birthdate)
from people; 

-- 요일을 문자열로 가져올때
select name, dayname(birthdate)
from people;

-- 요일을 숫자로 가져올때 1=Sunday, 2=Monday, 3=Tuesday, 4=Wednesday, 5=Thursday, 6=Friday, 7=Saturday)
select name, dayofweek(birthdate)
from people;

-- 시간도 각각 처리하는 함수가 있다
select name, hour(birthtime), minute(birthtime), second(birthtime)
from people;

select name, year(birthdt), hour(birthdt)
from people;

 

현재 시간, 날짜 가져오는 now(), curdate(), curtime()

-- 현재 시간을 구하는 방법 now() 함수
select now();

-- 현재의 년월일만 가져오고 싶을때 curdate() 함수
select curdate();

-- 현재의 시분초만 가져오고 싶을때 curtime() 함수
select curtime();

 

시간 형식 데이터를 사람이 보기 편한 문자열로 바꾸는 date_format()

-- db에 저장된 시간 형식의 데이터를
-- 사람이 보기 편한 문자열로 바꾸는 방법

-- 1990-11-11 10:07:35 => 1990년 11월 11일, 10시 7분 입니다.

select name, date_format(birthdt, '%Y년 %m월 %d일, %H시 %i분 입니다.')
from people;

 

시간의 차이를 구하는 datediff() 함수

-- 시간의 차이를 구하는 방법 : datediff() 함수
-- 현재 시간과 birthdt 시간의 차이를 구해보자. 현재 시간 - 태어난 시간

select datediff(now(), birthdt)
from people;

 

날짜에 n 값을 더하는 date_add, +

날짜에 n 값을 빼는 date_sub, -

-- 태어난 시간으로부터 100일 후의 날짜는?
select birthdt, date_add(birthdt, interval 100 day)
from people;

-- 태어난 시간으로부터 100일 전의 날짜는?
select birthdt, date_sub(birthdt, interval 100 day)
from people;

-- 태어난 시간으로부터 5주 후의 날짜는?
select birthdt, date_add(birthdt, interval 5 week)
from people;

-- 태어난 시간으로부터 72시간 후의 날짜는?
select birthdt, date_add(birthdt, interval 72 hour)
from people;

select birthdt, birthdt + interval 72 hour
from people;

select birthdt, birthdt - interval 72 hour
from people;

select birthdt, birthdt + interval 2 year + interval 27 hour - interval 29 minute
from people;

'MySQL' 카테고리의 다른 글

[MySQL] 테이블 Foreign Key 설정  (0) 2024.05.16
[MySQL] TIMESTAMP  (0) 2024.05.16
[MySQL] null 항목을 다른 값으로 채우기 ifnull()  (0) 2024.05.14
[MySQL] if() 함수  (0) 2024.05.14
[MySQL] case  (0) 2024.05.14