Received: from localhost (maia-1.hub.org [200.46.204.191]) by postgresql.org (Postfix) with ESMTP id 403C29FB324 for ; Mon, 4 Jun 2007 12:59:35 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.191]) (amavisd-maia, port 10024) with ESMTP id 39022-01 for ; Mon, 4 Jun 2007 12:59:31 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey-1.7.4 Received: from mtao04.charter.net (mtao04.charter.net [209.225.8.178]) by postgresql.org (Postfix) with ESMTP id 9AA779FA5D3 for ; Mon, 4 Jun 2007 12:59:31 -0300 (ADT) Received: from aa06.charter.net ([10.20.200.158]) by mtao04.charter.net (InterMail vM.7.08.02.00 201-2186-121-20061213) with ESMTP id <20070604155925.TWAW1527.mtao04.charter.net@aa06.charter.net>; Mon, 4 Jun 2007 11:59:25 -0400 Received: from [10.0.1.3] (really [66.188.164.45]) by aa06.charter.net with ESMTP id <20070604155925.XUIY21471.aa06.charter.net@[10.0.1.3]>; Mon, 4 Jun 2007 11:59:25 -0400 In-Reply-To: <20070604152736.GS32320@phlogiston.dyndns.org> References: <46642A05.40708@joshuaneil.com> <20070604152736.GS32320@phlogiston.dyndns.org> Mime-Version: 1.0 (Apple Message framework v752.2) Content-Type: text/plain; charset=US-ASCII; delsp=yes; format=flowed Message-Id: Cc: pgsql-sql@postgresql.org Content-Transfer-Encoding: 7bit From: Michael Glaesemann Subject: Re: current_date / datetime stuff Date: Mon, 4 Jun 2007 10:59:20 -0500 To: Andrew Sullivan X-Mailer: Apple Mail (2.752.2) X-Chzlrs: 0 X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200706/16 X-Sequence-Number: 28506 On Jun 4, 2007, at 10:27 , Andrew Sullivan wrote: > On Mon, Jun 04, 2007 at 10:04:37AM -0500, Joshua wrote: >> that will return the date of the first Monday of the month? > > I guess you need to write a function to do this. I suppose you could > do it by finding out what day of the week it is and what the date is, > then counting backwards to the earliest possible Monday. As Andrew said, there's no built-in function to do this, but it's easy enough to write one. Here's a rough example (very lightly tested and probably overly complicated) CREATE OR REPLACE FUNCTION first_dow(DATE, INTEGER) RETURNS DATE IMMUTABLE LANGUAGE SQL AS $_$ SELECT v_first_day_of_month + CASE WHEN v_day_of_week <= $2 THEN $2 - v_day_of_week ELSE 8 - v_day_of_week END AS first_day_of_month FROM ( SELECT v_first_day_of_month , extract('dow' from v_first_day_of_month)::integer AS v_day_of_week FROM (SELECT date_trunc('month', $1)::date) AS mon(v_first_day_of_month)) as calc; $_$; CREATE OR REPLACE FUNCTION first_monday(DATE) RETURNS DATE IMMUTABLE LANGUAGE SQL AS $_$ SELECT first_dow($1, 1); $_$; select first_monday(current_date); first_monday -------------- 2007-06-04 (1 row) select first_monday('2007-04-01'); first_monday -------------- 2007-04-02 (1 row) Michael Glaesemann grzm seespotcode net