Skip to content

time

Time and date functions — timestamps, component extraction, formatting.

Version v0.1
Platform PC, ESP32
Type Native (C)

star.mod

require dev-libs/time v0.1

Usage

import "time"

Functions

Current Time

Function Signature Description
time.now() () -> number Unix timestamp in seconds
time.nowMs() () -> number Unix timestamp in milliseconds
time.clock() () -> number Monotonic clock in milliseconds (for benchmarks)
var ts: number = time.now()        # 1748390400.0
var ms: number = time.nowMs()      # 1748390400123.0
var c1: number = time.clock()      # monotonic, unrelated to wall clock

time.now() and time.nowMs() return wall-clock time (affected by NTP adjustments). time.clock() returns monotonic time — it never goes backward, ideal for measuring elapsed time.

Component Extraction

Function Signature Description
time.year(ts) (number) -> i32 Year (e.g. 2025)
time.month(ts) (number) -> i32 Month (1-12)
time.day(ts) (number) -> i32 Day of month (1-31)
time.hour(ts) (number) -> i32 Hour (0-23)
time.minute(ts) (number) -> i32 Minute (0-59)
time.second(ts) (number) -> i32 Second (0-59)
time.weekday(ts) (number) -> i32 Day of week (0=Sunday, 6=Saturday)

All component functions take a unix timestamp (from time.now() or time.date()) and return the local time component.

var ts: number = time.now()
var y: i32 = time.year(ts)      # 2025
var m: i32 = time.month(ts)     # 5
var d: i32 = time.day(ts)       # 28
var h: i32 = time.hour(ts)      # 14
var wd: i32 = time.weekday(ts)  # 3 (Wednesday)

Creating Timestamps

Function Signature Description
time.date(y, m, d) (i32, i32, i32) -> number Create timestamp from year, month, day (midnight local)
var t: number = time.date(2025, 1, 1)
var y: i32 = time.year(t)    # 2025
var m: i32 = time.month(t)   # 1
var d: i32 = time.day(t)     # 1

Formatting

Function Signature Description
time.format(ts, fmt) (number, string) -> string Format timestamp using strftime format
var ts: number = time.date(2025, 5, 28)
var s: string = time.format(ts, "%Y-%m-%d")       # "2025-05-28"
var s2: string = time.format(ts, "%d/%m/%Y")       # "28/05/2025"
var s3: string = time.format(ts, "%H:%M:%S")       # "00:00:00"
var s4: string = time.format(ts, "%Y-%m-%d %H:%M") # "2025-05-28 00:00"

Common format specifiers:

Specifier Description Example
%Y 4-digit year 2025
%m Month (01-12) 05
%d Day (01-31) 28
%H Hour 24h (00-23) 14
%M Minute (00-59) 30
%S Second (00-59) 05
%A Weekday name Wednesday
%B Month name May
%a Short weekday Wed
%b Short month May

Full list follows C strftime — any valid strftime format works.

Notes

  • All timestamps are number (64-bit double) — unix seconds since 1970-01-01 UTC
  • Component extraction uses local time (system timezone)
  • time.clock() is monotonic — use it for measuring durations, not wall-clock time
  • On ESP32, time.now() requires NTP sync or RTC; time.clock() uses esp_timer