Function Getting the right week number of year

Houari picture Houari · Feb 13, 2013 · Viewed 11.6k times · Source

I want to create a function to get the right week number of year. I already posted here to find a 'native' solution, but apparently there is not.

I tryed to create funcrtion based on this mysql example

Here is the code translated to postgresql:

CREATE OR REPLACE FUNCTION week_num_year(_date date)    
RETURNS integer AS
$BODY$declare 
_year integer;
begin


select date_part('year',_date) into _year; 
return ceil((to_char(_date,'DDD')::integer+(to_char(('01-01-'||_year)::date,'D')::integer%7-7))/7);           


end;$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

But it gives wrong result, can someone help me ?

My config: PostgreSQL 9.2

Answer

Craig Ringer picture Craig Ringer · Feb 13, 2013

If you want proper week numbers use:

select extract(week from '2012-01-01'::date);

This will produce the result 52, which is correct if you look on a calendar.

Now, if you actually want to define week numbers as "Every 7 days starting with the first day of the year" that's fine, though it doesn't match the week numbers anyone else uses and has some odd quirks:

select floor((extract(doy from '2011-01-01'::date)-1)/7)+1;

By the way, parsing date strings and hacking them up with string functions is almost always a really bad idea.