I hope following query will give you the idea what I am looking for-
SELECT SUM(t1.hours) AS totalhours FROM
(
SELECT (time_to_sec(timediff(time_out, time_in)) / 3600) AS hours FROM bb_work_log
WHERE user_id = 6 AND (working_date BETWEEN '2014-04-01' AND '2014-04-31')
) AS t1
In my query, you can see the working_date
which I given here manually. But, I would not like to do it manually. I would like to pick first day and last day of current month dynamically.
To get yesterday's date, you need to subtract one day from today's date. Use CURDATE() to get today's date. In MySQL, you can subtract any date interval using the DATE_SUB() function. Here, since you need to subtract one day, you use DATE_SUB(CURDATE(), INTERVAL 1 DAY) to get yesterday's date.
The LAST_DAY() function in MySQL can be used to know the last day of the month for a given date or a datetime. The LAST_DAY() function takes a date value as argument and returns the last day of month in that date. The date argument represents a valid date or datetime. Syntax: LAST_DAY( Date );
MySQL DATE_FORMAT() Function The DATE_FORMAT() function formats a date as specified.
First day of Previous Month
select last_day(curdate() - interval 2 month) + interval 1 day
Last day of Previous Month
select last_day(curdate() - interval 1 month)
First day of Current Month
select last_day(curdate() - interval 1 month) + interval 1 day
Last day of Current Month
select last_day(curdate())
You can use LAST_DAY(NOW() - INTERVAL 1 MONTH) + INTERVAL 1 DAY
,which will subtract one month from now and by by adding 1 day in LAST_DAY
of previous month will give you the first day of current month
SELECT SUM(t1.hours) AS totalhours FROM
(
SELECT (time_to_sec(timediff(time_out, time_in)) / 3600) AS hours FROM bb_work_log
WHERE user_id = 6
AND (working_date BETWEEN LAST_DAY(NOW() - INTERVAL 1 MONTH)
AND LAST_DAY(NOW()))
) AS t1
LAST_DAY(NOW() - INTERVAL 1 MONTH) this will give you the last day of previous month
You can achieve it these ways ----
/* Current month*/
SELECT DATE_SUB(LAST_DAY(NOW()),INTERVAL DAY(LAST_DAY(NOW()))-1 DAY),CONCAT(LAST_DAY(NOW()),' 23:59:59');
SELECT LAST_DAY(CURDATE()) - INTERVAL DAY(LAST_DAY(CURDATE()))-1 DAY ,CONCAT(LAST_DAY(NOW()),' 23:59:59');
/* previous month*/
SELECT DATE_FORMAT(CURDATE() - INTERVAL 1 MONTH,'%Y-%m-01 00:00:00'),DATE_FORMAT(LAST_DAY(CURDATE()-INTERVAL 1 MONTH),'%Y-%m-%d 23:59:59');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With