mysql日期操作

1,简介

1)相加
select adddate(yearMonth, 1),month_sum_data.* from month_sum_data where yearMonth = "2017-08-01 00:00:00";
2)日期,时间,当前时间
select curdate(); 2017-09-17
select curtime(); 00:01:08
select current_timestamp; 2017-09-17 00:04:31
select now();2017-09-17 00:17:53
3)date差,加和减
select datediff(current_timestamp(), "2017-08-01 00:00:00");以天为单位
select adddate(current_timestamp(), 1);2017-09-18 00:11:33
select subdate(current_timestamp(), 1);2017-09-16 00:11:57
4)提取年,月,日,时,分,秒。
select year(now());2017
select month(now());9
select day(now());17
select hour(now());0
select minute(now());20
select second(now());28
5)格式化
date_format(date, format) 以format格式化date, 返回字符串。
select date_format(now(), "%Y~%m-%d %H~%m-%s")

2,应用

1)按月查数据每个月,该用户的消费额
select month(yearMonth), sum(amount)/100
from consum_data
where yearMonth >= "2017-01-01 00:00:00" and userId = 1
group by month(yearMonth);
2)按天查数据这段时间内,每天的新用户数量
select resultDay, count(*)
from (select id, date_format(createTime, "%Y-%m-%d") as resultDay
from user_account
where createTime between "2017-08-01 00:00:00" and "2017-08-31 00:00:00") as temp
group by resultDay order by resultDay asc;

你可能感兴趣的:(mysql日期操作)