MySQL 기초

[MySQL 날짜, 시간] curdate, now, day, date_add, date_format, datediff

jasonshin 2021. 12. 8. 11:40

-- 날짜와 시간 처리하는 방법

insert into people2
(name, birthdate, birthtime, birthdt)
values
('Padma', '1983-11-11', '10:07:35', '1983-11-11 10:07:35'), 
('Larry', '1990-12-25', '04:10:42', '1990-12-25 04:10:42');

select * from people2; 

-- 현재의 연월일 정보를 가져오는 함수 curdate()
select curdate();
-- 현재의 시간을 가져오는 함수 curtime()
select curtime();
-- 현재의 년원일 시분초를 가져오는 함수 now()
select now();

insert into people2
(name, birthdate, birthtime, birthdt)
values
('홍길동', curdate(), curtime(), now());

select * from people2;

select name, birthdate from people2;

select name, day(birthdate) from people2;

select name, dayname(birthdate) from people2;

select name, dayofweek(birthdate) from people2;

select name, dayofyear(birthdate) from people2;

select name, hour(birthtime) from people2;

select name, minute(birthtime) from people2;

select date_format(birthdt, '저는 %m/%d/%Y 에 태어났습니다.')
from people2; 

select date_format(birthdt, '저는 %h:%i 에 태어났습니다.')
from people2; 

select datediff(now(), birthdate)
from people2; 

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

select birthdt + interval 1 month from people2;

select birthdt + interval 15 month + interval 10 hour from people2;

 

-- timestamp 데이터 타입
create table comments (
content varchar (100),
    created_at timestamp default now()
);

insert into comments (content)
values ('안녕하세요');

select * from comments;

-- 댓글 수정할 경우 ==> 수정한 시간 저장!
create table comments2 (
content varchar (100),
    created_at timestamp default now(),
    changed_at timestamp default now() on update CURRENT_TIMESTAMP
);

insert into comments2 (content)
values ('안녕하세요');

select * from comments2; 

-- 댓글 수정하세요. 내용은 '반갑습니다' 
update comments2 
set content= '반갑습니다.'
where content= '안녕하세요';

select * from comments2; 

insert into comments2 (content)
values ('안녕하세요');

select * from comments2
order by created_at;

-- 현재 날짜를 화면에 출력하세요. 
select curdate();

-- 현재의 요일을 화면에 출력하세요.
select dayname(curdate());

-- 현재 날짜를 월/일/연도로 화면에 출력하세요.
select date_format(curdate(), '%m/%d/%Y');
select date_format(now(), '%m/%d/%Y');

반응형