lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Dave Collins <Dave.Collins@mercatustechnologies.com> wrote:

> My API delivers dates in the form yyyy-mm-dd but my design team wants
> DDD dd (i.e. Tue 14). Can anyone point me at a reliable algorithm for
> calculating day-of-week from a standard datestamp?

You can do it with Lua's os.date and os.time but this is more fun:

        local int = math.floor

        -- turn a Gregorian date into an RD number
        -- as defined in Calendrical Calculations
        -- Mon 0001-01-01 is RD 1
        -- Wed 1858-11-17 is RD 678576 and MJD 0
        -- Thu 1970-01-01 is RD 719163
        function rd(y,m,d)
                if m > 2
                then m = m + 1
                else m = m + 13; y = y - 1
                end
                return int(y*1461/4) - int(y/100) + int(y/400)
                     + int(m*153/5) + d - 428
        end

        local days = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }
        function dow(rd)
                return days[rd % 7 + 1]
        end

Tony.
-- 
f.anthony.n.finch  <dot@dotat.at>  http://dotat.at/
Forth, Tyne, Dogger: Southerly or southwesterly 3 or 4, increasing 5 at times.
Slight or moderate. Fair. Good.