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

后端 未结 8 1411
猫巷女王i
猫巷女王i 2020-11-30 03:47

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 quer

相关标签:
8条回答
  • 2020-11-30 04:23

    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))

    0 讨论(0)
  • 2020-11-30 04:27

    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
    
    0 讨论(0)
  • 2020-11-30 04:28

    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

    0 讨论(0)
  • 2020-11-30 04:34

    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!

    0 讨论(0)
  • 2020-11-30 04:35

    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

    0 讨论(0)
  • 2020-11-30 04:35
    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.

    0 讨论(0)
提交回复
热议问题