Merge 0.10->trunk
[prosody.git] / util / datetime.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 --
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9
10 -- XEP-0082: XMPP Date and Time Profiles
11
12 local os_date = os.date;
13 local os_time = os.time;
14 local os_difftime = os.difftime;
15 local tonumber = tonumber;
16
17 local _ENV = nil;
18
19 local function date(t)
20         return os_date("!%Y-%m-%d", t);
21 end
22
23 local function datetime(t)
24         return os_date("!%Y-%m-%dT%H:%M:%SZ", t);
25 end
26
27 local function time(t)
28         return os_date("!%H:%M:%S", t);
29 end
30
31 local function legacy(t)
32         return os_date("!%Y%m%dT%H:%M:%S", t);
33 end
34
35 local function parse(s)
36         if s then
37                 local year, month, day, hour, min, sec, tzd;
38                 year, month, day, hour, min, sec, tzd = s:match("^(%d%d%d%d)%-?(%d%d)%-?(%d%d)T(%d%d):(%d%d):(%d%d)%.?%d*([Z+%-]?.*)$");
39                 if year then
40                         local time_offset = os_difftime(os_time(os_date("*t")), os_time(os_date("!*t"))); -- to deal with local timezone
41                         local tzd_offset = 0;
42                         if tzd ~= "" and tzd ~= "Z" then
43                                 local sign, h, m = tzd:match("([+%-])(%d%d):?(%d*)");
44                                 if not sign then return; end
45                                 if #m ~= 2 then m = "0"; end
46                                 h, m = tonumber(h), tonumber(m);
47                                 tzd_offset = h * 60 * 60 + m * 60;
48                                 if sign == "-" then tzd_offset = -tzd_offset; end
49                         end
50                         sec = (sec + time_offset) - tzd_offset;
51                         return os_time({year=year, month=month, day=day, hour=hour, min=min, sec=sec, isdst=false});
52                 end
53         end
54 end
55
56 return {
57         date     = date;
58         datetime = datetime;
59         time     = time;
60         legacy   = legacy;
61         parse    = parse;
62 };