Received: from localhost (maia-2.hub.org [200.46.204.187]) by postgresql.org (Postfix) with ESMTP id C78AB9FBB44 for ; Mon, 4 Jun 2007 13:39:35 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.187]) (amavisd-maia, port 10024) with ESMTP id 35033-03-6 for ; Mon, 4 Jun 2007 13:39:28 -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 491B69FBCF7 for ; Mon, 4 Jun 2007 13:39:28 -0300 (ADT) Received: from aa07.charter.net ([10.20.200.159]) by mtao04.charter.net (InterMail vM.7.08.02.00 201-2186-121-20061213) with ESMTP id <20070604163927.YAPN1527.mtao04.charter.net@aa07.charter.net>; Mon, 4 Jun 2007 12:39:27 -0400 Received: from [10.0.1.3] (really [66.188.164.45]) by aa07.charter.net with ESMTP id <20070604163927.GWYG12201.aa07.charter.net@[10.0.1.3]>; Mon, 4 Jun 2007 12:39:27 -0400 In-Reply-To: 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: <7B00D29F-089A-4A19-B9C1-0FF8A949DDA3@seespotcode.net> Cc: Andrew Sullivan , pgsql-sql@postgresql.org Content-Transfer-Encoding: 7bit From: Michael Glaesemann Subject: Re: current_date / datetime stuff Date: Mon, 4 Jun 2007 11:39:21 -0500 To: Michael Glaesemann X-Mailer: Apple Mail (2.752.2) X-Chzlrs: 0 X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200706/18 X-Sequence-Number: 28508 On Jun 4, 2007, at 10:59 , Michael Glaesemann wrote: > > 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) And a little simpler: CREATE OR REPLACE FUNCTION first_dow_of_month(DATE, INTEGER) RETURNS DATE IMMUTABLE LANGUAGE SQL AS $_$ SELECT v_first_day_of_month + ( 7 + $2 - v_day_of_week) % 7 AS first_dow_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_of_month($1, 1); $_$; Michael Glaesemann grzm seespotcode net