Working with time

Webhook Relay provides several helpers when working with time, this section shows how to get current time, how to parse and format time

To get current time in Unix format:

local time = require("time")

local now = time.unix()

r:SetRequestBody(tostring(now_unix))

-- Will set body to such as '1692450481.8626223'

Formatting time

Formatting time with Webhook Relay is a bit different from other languages’ approaches. Whereas other languages use a format like YYYY-MM-DD to format dates like: 2022-10-21, WHR uses a reference time.

This reference time is a point in time that the language will use to parse your layout : - 2 January 2006 03:04:05 PM in the time zone UTC -7

You might ask why this particular date. That’s because when you read it like that :

01/02 03:04:05PM '06 -0700

You can note that numbers follow each other: 1 (January), 2 (day), 3 (hour), 4(minutes)…

local time = require("time")

-- Get current time
local now = time.unix()

-- Declare the layout
local layout = "2006-01-02T15:04:05Z07:00"

-- Format it in our layout
local now_human_readable = time.format(now, layout)

r:SetRequestBody(now_human_readable)

-- prints out 2023-08-19T13:21:32Z

More example layouts:

Layout      = "01/02 03:04:05PM '06 -0700" // The reference time, in numerical order.
ANSIC       = "Mon Jan _2 15:04:05 2006"
UnixDate    = "Mon Jan _2 15:04:05 MST 2006"
RubyDate    = "Mon Jan 02 15:04:05 -0700 2006"
RFC822      = "02 Jan 06 15:04 MST"
RFC822Z     = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
RFC850      = "Monday, 02-Jan-06 15:04:05 MST"
RFC1123     = "Mon, 02 Jan 2006 15:04:05 MST"
RFC1123Z    = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
RFC3339     = "2006-01-02T15:04:05Z07:00"
RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
Kitchen     = "3:04PM"
// Handy time stamps.
Stamp      = "Jan _2 15:04:05"
StampMilli = "Jan _2 15:04:05.000"
StampMicro = "Jan _2 15:04:05.000000"
StampNano  = "Jan _2 15:04:05.000000000"

Parsing time

Parsing works the same way as formatting time, you will need to provide a time and the layout. Result will be returned as a Unix timestamp.

time.parse("Dec 2 03:33:05 2018", "Jan 2 15:04:05 2006")

Timezones

To format the time for some particular timezone, you can pass the third optional parameter into the `time.format()` function, for example:

local time = require("time")

local now = time.unix()

local layout = "01.02.2006 15:04"

local now_human_readable, err = time.format(now, layout, "CET")
if err then error(err) end

r:SetRequestBody(now_human_readable)

Last updated