Skip to content

Instantly share code, notes, and snippets.

@arbo77
Created January 26, 2017 22:48
Show Gist options
  • Save arbo77/a0e935569d70fd18e54209cd891d1337 to your computer and use it in GitHub Desktop.
Save arbo77/a0e935569d70fd18e54209cd891d1337 to your computer and use it in GitHub Desktop.
PostgreSQL 1 month calendar dates
create or replace function kalender(p_tahun int, p_bulan int) returns text LANGUAGE plpgsql
AS $function$
declare
y int;
m int;
d_start date;
d_end date;
nb int;
c int;
l text;
begin
select
tahun,
bulan,
case when hari_pertama > 0 then
hari - interval '1 days' * hari_pertama
else to_date(concat(tahun,'-',bulan,'-1'),'yyyy-mm-dd')
end as tgl_pertama,
tgl_terakhir
from (
select
date_part('dow',
to_date(concat(p_tahun,'-',p_bulan,'-01'),'yyyy-mm-dd')
) as hari_pertama,
to_date(concat(p_tahun,'-',p_bulan,'-01'),'yyyy-mm-dd') + interval '1 months' - interval '1 days' as tgl_terakhir,
to_date(concat(p_tahun,'-',p_bulan,'-01'),'yyyy-mm-dd') as hari,
date_part('day',to_date(concat(p_tahun,'-',p_bulan,'-01'),'yyyy-mm-dd')) as hari_ini,
date_part('month',to_date(concat(p_tahun,'-',p_bulan,'-01'),'yyyy-mm-dd')) as bulan,
date_part('year',to_date(concat(p_tahun,'-',p_bulan,'-01'),'yyyy-mm-dd')) as tahun
) a
into y,m,d_start,d_end;
c = 0;
l = '';
loop
if c = 35 then
exit;
end if;
l = concat(l,'"',to_char(d_start + interval '1 days' * c,'yyyy-mm-dd'),'",');
c = c + 1;
end loop;
-- return l;
-- return concat('{"tahun":',y,',"bulan":',m,',"tanggal":{"awal":',to_char(d_start,'dd')::int,',"akhir":',to_char(d_end,'dd')::int,'}',l,'}');
return concat('{"tahun":',y,',"bulan":',m,',"tanggal":[',substring(l,0,length(l)),']}');
end;
$function$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment