MySQL round date to the start of the week and month - mysql

For "2012-07-12", how can I get the start of the week, i.e., "2012-07-08", and start of the month, i.e., "2012-07-01"?

First day of the month:
SELECT DATE_FORMAT('2007-07-12', '%Y-%m-01');
output: 2007-07-01
First day of the week:
SELECT DATE_SUB('2007-07-12', INTERVAL DAYOFWEEK('2007-07-12')-1 DAY);
output: 2007-07-08
MySQL reference: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add

Same answer as Borophyll's, but I have changed the behavior of the first day of the month to return a date, not just a string which avoids date formatting/parsing mentioned in user151220's answer.
First day of the month:
SELECT DATE_SUB('2007-07-12', INTERVAL DAYOFMONTH('2007-07-12') - 1 DAY);
output: 2007-07-01
First day of the week:
SELECT DATE_SUB('2007-07-12', INTERVAL DAYOFWEEK('2007-07-12') - 1 DAY);
output: 2007-07-08
MySQL reference: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add

For those who need Monday as the first day of the week:
SELECT DATE_SUB('2007-07-12', INTERVAL WEEKDAY('2007-07-12') DAY);
output: 2007-07-09
This relies on the WEEKDAY function, which starts with Monday instead of DAYOFWEEK, which starts with Sunday.

The DATE_FORMAT reply from Borophyll is very good, but gives a string rather than a date. So can't be compared easily.
If you need to use this as a comparison to a date field, use str_to_date to reverse it back to date rather than string.
select x from y where date >= str_to_date( DATE_FORMAT(now()-interval 12 month,'Y-%m-01'), '%Y-%m-%d')
If you are (say) looking at 12 months sales figures, but you want to always start off from the 1st of a month.

This will work if you want to just code it and forget about it, it will use datetime now and always return MTD results-
where date_completed between date_sub(date(now()), INTERVAL dayofmonth(now()) -1 day) and now()

Related

MySQL- How can I extract the monday given a number of week?

Essentially what I want to obtain is the monday given the number of the week::
I have week: 9, 7,5
This number of week corresponds to a timestamp:
2019-03-02 02:48:00,
2019-02-15 02:58:00,
2019-01-31 00:25:00
I want to obtain the date of the monday of this week(first day of week):
2/25,
2/11,
1/28
How can extract this outout? it can be extracted from timestamp if it is easier
If you want to get Monday of the week.
You can try to use DATE_ADD and WEEKDAY function.
SELECT DATE_ADD(dt, INTERVAL - WEEKDAY(dt) DAY)
FROM T
sqlfiddle
EDIT
There is another function DATE_FORMAT represent to the date format string.
using "%m/%d"
SELECT DATE_FORMAT(
DATE_ADD(dt, INTERVAL - WEEKDAY(dt) DAY), "%m/%d")
FROM T
sqlfiddle

How to find next date from time in mysql

I want to know is it possible in mysql query.. when I say give me date when it is 9am.. the return answer is depends upon current time when it is 8am it give me today's date. when it is 10pm it gives me tomorrow date. how it is possible in mysql query.
You can use SUBSTRING_INDEX(CURTIME(), ':', 1) to get the hours of current time.
As I understood you want to get tomorrow date, if it is 10pm or later
Example given:
SELECT
CASE
WHEN SUBSTRING_INDEX(CURTIME(), ':', 1) >= 22
THEN DATE_ADD(CURDATE(), INTERVAL 1 DAY)
ELSE CURDATE()
END
Source: http://www-db.deis.unibo.it/courses/TW/DOCS/w3schools/sql/sql_dates.asp.html
You can get the hour value from a given datetime expression, using HOUR function. CURDATE() function is used to return the current date. You can add/subtract 'integers' to it get the date corresponding to current date +/- 'integer days' . Assuming that the time >= 10 pm returns next day:
SELECT IF(HOUR(`datetime_field`) > 22, CURDATE(), CURDATE() + 1);
You could just add 2 hours
SELECT DATE(DATE_ADD(NOW(), INTERVAL 2 HOUR));
This will then return tomorrow’s date for anytime after 10pm.

Is there a way to get the First day of the previous month and Last day of current month?

Here I need a function in MySQL where it returns
Dates
Starting date of previous month
Last date of current month.
starting date of previous month
select date_format(curdate() - interval 1 month,'%Y-%m-01 00:00:00')
last date of current month
select date_format(last_day(curdate()),'%Y-%m-%d 23:59:59')
You would use NOW() to get the current date and time. MONTH() to get the current month. And using that value, you can get the previous month and the next month. see http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
Last day of current month:
select last_day(now())
Starting date of previous month:
select adddate(subdate(last_day(now()), interval 2 month), 1)

How do I get the first day of the week of a date in mysql?

Suppose I have 2011-01-03 and I want to get the first of the week, which is sunday, which is 2011-01-02, how do I go about doing that?
The reason is I have this query:
select
YEAR(date_entered) as year,
date(date_entered) as week, <-------This is what I want to change to select the first day of the week.
SUM(1) as total_ncrs,
SUM(case when orgin = picked_up_at then 1 else 0 end) as ncrs_caught_at_station
from sugarcrm2.ncr_ncr
where
sugarcrm2.ncr_ncr.date_entered > date('2011-01-01')
and orgin in(
'Silkscreen',
'Brake',
'Assembly',
'Welding',
'Machining',
'2000W Laser',
'Paint Booth 1',
'Paint Prep',
'Packaging',
'PEM',
'Deburr',
'Laser ',
'Paint Booth 2',
'Toolpath'
)
and date_entered is not null
and orgin is not null
AND(grading = 'Minor' or grading = 'Major')
and week(date_entered) > week(current_timestamp) -20
group by year, week(date_entered)
order by year asc, week asc
And yes, I realize that origin is spelled wrong but it was here before I was so I can't correct it as too many internal apps reference it.
So, I am grouping by weeks but I want this to populate my chart, so I can't have all the beginning of weeks looking like different dates. How do I fix this?
If the week starts on Sunday do this:
DATE_ADD(mydate, INTERVAL(1-DAYOFWEEK(mydate)) DAY)
If the week starts on Monday do this:
DATE_ADD(mydate, INTERVAL(-WEEKDAY(mydate)) DAY);
more info
If you need to handle weeks which start on Mondays, you could also do it that way. First define a custom FIRST_DAY_OF_WEEK function:
DELIMITER ;;
CREATE FUNCTION FIRST_DAY_OF_WEEK(day DATE)
RETURNS DATE DETERMINISTIC
BEGIN
RETURN SUBDATE(day, WEEKDAY(day));
END;;
DELIMITER ;
And then you could do:
SELECT FIRST_DAY_OF_WEEK('2011-01-03');
For your information, MySQL provides two different functions to retrieve the first day of a week. There is DAYOFWEEK:
Returns the weekday index for date (1 = Sunday, 2 = Monday, …, 7 = Saturday). These index values correspond to the ODBC standard.
And WEEKDAY:
Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday).
If week starts on Monday
SELECT SUBDATE(mydate, weekday(mydate));
If week starts on Sunday
SELECT SUBDATE(mydate, dayofweek(mydate) - 1);
Example:
SELECT SUBDATE('2018-04-11', weekday('2018-04-11'));
2018-04-09
SELECT SUBDATE('2018-04-11', dayofweek('2018-04-11') - 1);
2018-04-08
Week starts day from sunday then get First date of the Week and Last date of week
SELECT
DATE("2019-03-31" + INTERVAL (1 - DAYOFWEEK("2019-03-31")) DAY) as start_date,
DATE("2019-03-31" + INTERVAL (7 - DAYOFWEEK("2019-03-31")) DAY) as end_date
Week starts day from Monday then get First date of the Week and Last date of week
SELECT
DATE("2019-03-31" + INTERVAL ( - WEEKDAY("2019-03-31")) DAY) as start_date,
DATE("2019-03-31" + INTERVAL (6 - WEEKDAY("2019-03-31")) DAY) as end_date
select '2011-01-03' - INTERVAL (WEEKDAY('2011-01-03')+1) DAY;
returns the date of the first day of week. You may look into it.
This is a much simpler approach than writing a function to determine the first day of a week.
Some variants would be such as
SELECT DATE_ADD((SELECT CURDATE() - INTERVAL (WEEKDAY(CURDATE())+1)DAY),INTERVAL 7 DAY) (for the ending date of a query, such as between "beginning date" and "ending date").
SELECT CURDATE() - INTERVAL (WEEKDAY(CURDATE())+1) DAY (for the beginning date of a query).
This will return all values for the current week. An example query would be as follows:
SELECT b.foo FROM bar b
WHERE b.datefield BETWEEN
(SELECT CURDATE() - INTERVAL (WEEKDAY(CURDATE())+1) DAY)
AND (SELECT DATE_ADD((SELECT CURDATE() - INTERVAL (WEEKDAY(CURDATE())+1)DAY),INTERVAL 7 DAY))
This works form me
Just make sure both dates in the below query are the same...
SELECT ('2017-10-07' - INTERVAL WEEKDAY('2017-10-07') Day) As `mondaythisweek`
This query returns: 2017-10-02 which is a monday,
But if your first day is sunday, then just subtract a day from the result of this and wallah!
If the week starts on Monday do this:
DATE_SUB(mydate, INTERVAL WEEKDAY(mydate) DAY)
SELECT MIN(DATE*given_date*) FROM *table_name*
This will return when the week started at for any given date.
Keep the good work going!

Need mySQL TIMESTAMP for begining of the current week or any given date?

I need mySQL timestamp for start of current week or any given date, if week starts with monday?
I'm trying something like:
SELECT UNIX_TIMESTAMP(CONCAT( DATE_SUB(CURDATE(), INTERVAL WEEKDAY(DATE_SUB(CURDATE(), INTERVAL 7 DAY)) DAY), ' 00:00:00')) as start
Monday has a dayofweek index=2. DAYOFWEEK($date) gives the index of the day (1-7, Sun-Sat). So, you need to add or subtract days from your $date's index to change it to 2.
e.g.
SELECT UNIX_TIMESTAMP(
CASE WHEN DAYOFWEEK($date)>=2
THEN DATE_SUB($date, INTERVAL (DAYOFWEEK($date)-2) DAYS)
ELSE DATE_ADD($date INTERVAL 1 DAY)
END
);
I think I've got the syntax right on this, but check CASE and date and time functions.