e440219a9c8a443ecf48ded41bf70871e6509eac
[project/luci.git] / modules / luci-base / luasrc / http / protocol / date.lua
1 -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org>
2 -- Licensed to the public under the Apache License 2.0.
3
4 -- This class contains functions to parse, compare and format http dates.
5 module("luci.http.protocol.date", package.seeall)
6
7 require("luci.sys.zoneinfo")
8
9
10 MONTHS = {
11 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
12 "Sep", "Oct", "Nov", "Dec"
13 }
14
15 function tz_offset(tz)
16
17 if type(tz) == "string" then
18
19 -- check for a numeric identifier
20 local s, v = tz:match("([%+%-])([0-9]+)")
21 if s == '+' then s = 1 else s = -1 end
22 if v then v = tonumber(v) end
23
24 if s and v then
25 return s * 60 * ( math.floor( v / 100 ) * 60 + ( v % 100 ) )
26
27 -- lookup symbolic tz
28 elseif luci.sys.zoneinfo.OFFSET[tz:lower()] then
29 return luci.sys.zoneinfo.OFFSET[tz:lower()]
30 end
31
32 end
33
34 -- bad luck
35 return 0
36 end
37
38 function to_unix(date)
39
40 local wd, day, mon, yr, hr, min, sec, tz = date:match(
41 "([A-Z][a-z][a-z]), ([0-9]+) " ..
42 "([A-Z][a-z][a-z]) ([0-9]+) " ..
43 "([0-9]+):([0-9]+):([0-9]+) " ..
44 "([A-Z0-9%+%-]+)"
45 )
46
47 if day and mon and yr and hr and min and sec then
48 -- find month
49 local month = 1
50 for i = 1, 12 do
51 if MONTHS[i] == mon then
52 month = i
53 break
54 end
55 end
56
57 -- convert to epoch time
58 return tz_offset(tz) + os.time( {
59 year = yr,
60 month = month,
61 day = day,
62 hour = hr,
63 min = min,
64 sec = sec
65 } )
66 end
67
68 return 0
69 end
70
71 function to_http(time)
72 return os.date( "%a, %d %b %Y %H:%M:%S GMT", time )
73 end
74
75 function compare(d1, d2)
76
77 if d1:match("[^0-9]") then d1 = to_unix(d1) end
78 if d2:match("[^0-9]") then d2 = to_unix(d2) end
79
80 if d1 == d2 then
81 return 0
82 elseif d1 < d2 then
83 return -1
84 else
85 return 1
86 end
87 end