oracle uses to_date to query the first day of the week

  • 2021-10-27 09:40:40
  • OfStack

Week is calculated by IW method. If there are more than or equal to 4 days between the 52nd week of a year and December 31st of the current year, it will be designated as the 53rd week of the current year, otherwise the remaining days will be classified as the 1st week of the next year


CREATE OR REPLACE FUNCTION f_week_to_date(a_week varchar2) RETURN CHAR IS  
  v_first_date   char(10);  
  v_date_of_week number(1);  

BEGIN  
  select to_char(to_date(substr(a_week, 1, 4) || '0101', 'yyyymmdd'), 'D')  
    into v_date_of_week  
    from dual;  
  v_date_of_week := v_date_of_week - 1;  
  if v_date_of_week <= 4 then  
    select TO_CHAR(TO_DATE(SUBSTR(a_week, 1, 4) || '0101', 'yyyymmdd') +  
                   SUBSTR(a_week, 5, 2) * 7 - 7 - v_date_of_week + 1,  
                   'yyyy-mm-dd')  
      into v_first_date  
      from dual;  
  else  
    select TO_CHAR(TO_DATE(SUBSTR(a_week, 1, 4) || '0101', 'yyyymmdd') +  
                   SUBSTR(a_week, 5, 2) * 7  - v_date_of_week + 1,  
                   'yyyy-mm-dd')  
      into v_first_date  
      from dual;  
  end if;  

  return v_first_date;  

END;


Related articles: