본문 바로가기
MySQL

[MySQL] 날짜와 시간 처리하기

by coding_su 2022. 12. 7.

📝MySQL Workbench 날짜와 시간 처리하기

데이터에서 일, 월, 요일, 시간 등 정보 가져오기

-- 일 정보 가져오기
select name, day(birthdate)
from people2;
select name, dayofmonth(birthdate)
from people2;

-- 요일 정보 가져오기(Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday)
select name, dayname(birthdate)
from people2;

-- 숫자로 요일 정보 가져오기(1=Sunday, 2=Monday, 3=Tuesday, 4=Wednesday, 5=Thursday, 6=Friday, 7=Saturday)
select name, dayofweek(birthdate)
from people2;

-- 365일중 몇일째인지 가져오기
select name, dayofyear(birthdate)
from people2;

-- 월 정보 가져오기
select name, month(birthdate)
from people2;

-- 시간, 분, 초 정보 가져오기
select name, hour(birthdt), minute(birthdt), second(birthdt)
from people2;

 

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

-- 현재 시간을 가져오기 now()
select now();

-- 현재의 년,월,일만 가져오기 curdate()
select curdate();

-- 현재의 시분초만 가져오기 curtime()
select curtime();

 

시간형식의 데이터를 보기 편한 데이터로 바꾸기 date_format()

-- 바꿀 컬럼값, 조건 입력 
select date_format(birthdt, '%Y년 %m월 %d일 %h시')
from people2;

 

날짜, 시간 차이를 구하기 datediff()

-- birthdt 과 현재시간의 차이를 구하기
select datediff(now(), birthdt)
from people2;

 

날짜에 n값을 더하거나 빼기

-- 원래 있던 날짜에 n일을 더하기
select birthdt, date_add(birthdt, interval 1 day)
from people2;

select birthdt, date_add(birthdt, interval 3 month)
from people2;

select birthdt, date_add(birthdt, interval 7 hour)
from people2;

-- 원래 있던 날짜에 n일을 빼기
select birthdt, date_sub(birthdt, interval 7 day)
from people2;

-- 그냥 더하기나 빼기도 가능
select birthdt, birthdt + interval 7 day
from people2;

select birthdt, birthdt - interval 7 day + interval 3 hour
from people2;

댓글