summaryrefslogtreecommitdiffstats
path: root/aconf/model/time.lua
blob: 5879bc35cd9e69961c2ebe8cd974f6a0d07a546e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
--[[
Copyright (c) 2012-2015 Kaarle Ritvanen
See LICENSE file for license details
--]]

local M = {}

local raise = require('aconf.error').raise

local object = require('aconf.object')
local class = object.class
local super = object.super


local posix = require('posix')


M.Timestamp = class(require('aconf.model.field').String)
M.Date = class(M.Timestamp)
M.Time = class(M.Timestamp)

M.Date.format = '%Y-%m-%d'
M.Time.format = '%H:%M:%S'
M.Timestamp.format = M.Date.format..' '..M.Time.format

function M.Timestamp:_offset(value)
   if not value then return end
   if type(value) == 'number' then return value end
   local time = posix.strptime(value, self.format)
   return time and os.time(time)
end

function M.Timestamp:decode(context, value)
   return value and self.epoch_offset and os.date(self.format, value) or value
end

function M.Timestamp:encode(context, value)
   return self.epoch_offset and self:_offset(value) or value
end

function M.Timestamp:normalize(context, value)
   local time = self:_offset(value)
   return time and os.date(self.format, time) or value
end

function M.Timestamp:validate(context, value)
   super(self, M.Timestamp):validate(context, value)
   if not self:_offset(value) then raise(context.path, 'Invalid value') end
end

function M.Date:init(params)
   super(self, M.Date):init(params)
   self.widget = 'date'
end

function M.Time:init(params)
   super(self, M.Time):init(params)
   if params.seconds == false then self.format = '%H:%M' end
end


return M