time

The time module provides time constants and conversion functions.

def time = use('time')

time is the module; $clock is the endowment. Asking a machine what time it is is not uniform enough to be one C surface, so $clock is asynchronous everywhere — you give it a callback and it comes back with the time — and the per-platform time surface sits underneath it. time is built on that raw reading and gives you the calendar arithmetic around it.

Constants

ConstantValueDescription
time.second1Seconds in a second
time.minute60Seconds in a minute
time.hour3600Seconds in an hour
time.day86400Seconds in a day
time.week604800Seconds in a week
time.month2629746Seconds in a month (30.44 days)
time.year31556952Seconds in a year (365.24 days)

Getting Current Time

time.now()

Get the current wall-clock time as seconds since the Unix epoch, using the highest resolution the platform provides.

time.number()

With no argument, this is an alias for time.now(). With an argument, it converts a time record or formatted text to seconds since the Unix epoch.

time.monotonic()

Get monotonic seconds since the Pit process started. Use this for durations, timeouts, benchmarks, profiling, and any measurement that should not jump when the system clock changes.

time.record()

Get current time as a record.

var now = time.record()
// {second: 45, minute: 30, hour: 10, yday: 14, year: 2024,
//  weekday: 1, month: 0, day: 15, zone: 0, dst: false, ce: "AD"}

month counts from 0, so January is 0 and December is 11. day counts from 1. yday is the day of the year, weekday the day of the week, and zone the offset in seconds from UTC.

time.text(format)

Get current time as formatted text.

time.text()                      // "January Mon 15 10:30:45 AM +0000 2024 AD"
time.text("y-mm-d hh:nn:ss")     // "2024-01-15 10:30:45"

Format tokens:

TokenMeans
y, yyyyyear
m, mmmonth number, counting from 1
mb, mBmonth name, short or full
d, ddday of month
h, hhhour
n, nnminute
s, sssecond
v, vb, vBweekday, short or full
aAM or PM
zzone offset
cera

Converting Time

time.number(record)

Convert record to timestamp.

time.number({year: 2024, month: 1, day: 15})

time.text(number, format, zone)

Format timestamp as text.

time.text(1702656000, "yyyy-MM-dd")  // "2024-01-15"

time.record(number)

Convert timestamp to record.

time.record(1702656000)
// {year: 2024, month: 1, day: 15, ...}

Time Arithmetic

def time = use('time')

var now = time.number()

// Tomorrow at this time
var tomorrow = now + time.day

// One week ago
var last_week = now - time.week

// In 2 hours
var later = now + (2 * time.hour)

// Format future time
log.console(time.text(tomorrow))

Example

def time = use('time')

// Measure execution time
var start = time.monotonic()
// ... do work ...
var elapsed = time.monotonic() - start
log.console(`Took ${elapsed} seconds`)

// Schedule for tomorrow
var tomorrow = time.number() + time.day
log.console(`Tomorrow: ${time.text(tomorrow, "yyyy-MM-dd")}`)