Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First day of week (beginning with Sunday)

I found that there is a function last_day for last day of month, and date_part(dow, date) for numeric day of week starting with Sunday, but I am trying to take a date, and get the first day of that week.

Meaning: if date='2018-02-14' then result should be '2018-02-11'.

Any ideas?

like image 345
user8834780 Avatar asked Dec 08 '22 15:12

user8834780


2 Answers

You simply want to subtract the dow value from the current date.

select dateadd(d, -datepart(dow, my_date), my_date)  
from (select date('2018-02-14') as my_date)

> 2018-02-11 00:00:00.0

For example, if dow is 3 for 2018-02-14 - a Wednesday - you can subtract 3 days to get back to "day 0".


There's also the date_trunc function which will truncate everything after a given datepart. This is a little clunky, and will only set you back to the previous Monday, not Sunday.

select date_trunc('week', my_date)
from (select date('2018-02-14') as my_date)
like image 200
Kirk Broadhurst Avatar answered Dec 29 '22 11:12

Kirk Broadhurst


Not sure if there is a more efficient solution but:

date_trunc('week',my_date + '1 day'::interval)::date - '1 day'::interval as week_start
like image 36
Matt Clark Avatar answered Dec 29 '22 12:12

Matt Clark