silk.time.pattern.
Writes and reads dates and times with strftime patterns, such as %Y-%m-%d %H:%M:%S %z.
When to use#
Use TimePattern for a date format that is not ISO 8601: a log line, a file name, a date
in a form that a person typed, or the format of another program. For ISO 8601 text, the
parse and Display of the time types are shorter and faster.
Details#
A pattern is literal text and directives. A directive is %, optional flags, an optional
width, and one letter.
| Directive | Meaning | Example |
|---|---|---|
%Y | Year, four digits or more | 2026 |
%C | Century, the year divided by 100 | 20 |
%y | Year in the century, 00 to 99 | 26 |
%m | Month, 01 to 12 | 11 |
%B, %b, %h | English month name, full or three letters | November, Nov |
%d | Day of the month, 01 to 31 | 09 |
%e | Day of the month, padded with a space | 9 |
%j | Day of the year, 001 to 366 | 323 |
%A, %a | English weekday name, full or three letters | Thursday, Thu |
%u | Weekday, 1 for Monday to 7 for Sunday | 4 |
%w | Weekday, 0 for Sunday to 6 for Saturday | 4 |
%G, %g | Year of the ISO 8601 week, whole or two digits | 2026, 26 |
%V | ISO 8601 week, 01 to 53 | 47 |
%U | Week of the year with Sunday first, 00 to 53 | 46 |
%W | Week of the year with Monday first, 00 to 53 | 46 |
%H | Hour, 00 to 23 | 18 |
%k | Hour, 0 to 23, padded with a space | 18 |
%I | Hour of the 12-hour clock, 01 to 12 | 06 |
%l | Hour of the 12-hour clock, padded with a space | 6 |
%p, %P | AM or PM, and am or pm | PM, pm |
%M | Minute, 00 to 59 | 36 |
%S | Second, 00 to 59 | 22 |
%f | Fraction of a second, without zeros at the end | 5 |
%N | Fraction of a second, nine digits | 500000000 |
%z | UTC offset; %:z has a colon, %::z has seconds | +0100, +01:00 |
%Z | Abbreviation of the time zone. It cannot be read. | CET |
%s | Seconds from the Unix epoch | 1795109782 |
%F | %Y-%m-%d | 2026-11-19 |
%T, %X | %H:%M:%S | 18:36:22 |
%R | %H:%M | 18:36 |
%D, %x | %m/%d/%y | 11/19/26 |
%r | %I:%M:%S %p | 06:36:22 PM |
%c | %a %b %e %H:%M:%S %Y | Thu Nov 19 18:36:22 2026 |
%n, %t, %% | A line feed, a tab, and % |
The flags are - for no padding, _ for padding with spaces, 0 for padding with zeros, and
^ for upper case. A width, such as the 3 of %3f, sets the least number of characters,
and for %f and %N the exact number of digits. %.f writes a point and the fraction, and
nothing for a whole second.
A pattern that is a constant is checked when the program is compiled: an unknown directive, or
a directive that the value cannot supply, such as %H for a PlainDate, is a compile error.
The functions with Dynamic in the name take a pattern that is known only at run time and
report the same problems as a PatternError.
A year before 0 has a minus sign before its digits, as in -0044, and a width counts the
sign.
Reading is lenient about digits and space: a number can have fewer digits than its width,
white space in the pattern matches any amount of white space, a directive that is padded
with spaces (%e, %k, %l, or the flag _) can have spaces before it, and names match in
any case, in the full or the short form. A year can have a sign, and then up to six digits.
%z reads Z, +01, +0100, +01:00, and the forms with seconds. The text must end where
the pattern ends.
A date is read from a year with a month and a day, a day of the year, or a week and a weekday. A two-digit year without a century is from 1969 to 2068. A time of day needs an hour; the minute and the second are 0 if the pattern has none.
Gotchas#
The names are English only. Names in other languages belong to a locale library.
Examples#
Read a date and write it in another form#
import silk.core.effect { Effect }
import silk.core.result { Result }
import silk.mem.allocator { Allocator, OutOfMemoryError }
import silk.text.string { String }
import silk.time.pattern { TimePattern }
import silk.time.plain_date { PlainDate }
import silk.time.text { TimeParseError }
effect fn long(text: string) -> String ! OutOfMemoryError ? &mut Allocator {
return match TimePattern.parse<PlainDate>("%d/%m/%Y", text) {
Result<PlainDate, TimeParseError>.Success { value } => run TimePattern.format("%A, %B %-d, %Y", &value)
Result<PlainDate, TimeParseError>.Failure {..} => run String.copy("not a date")
}
}
pub effect fn main() -> i32 ! OutOfMemoryError {
let mut allocator = Allocator.systemAllocatorProvider()
let written = run long("19/11/2026") |> Effect.provideMut<Allocator>(&mut allocator)
return if written.view() == "Thursday, November 19, 2026" { 0 } else { 1 }
}Import as TimePattern with import silk.time.pattern { TimePattern }.
Public declarations: 9.
PatternReason#
pub enum PatternReasonThe cause of a PatternError.
UnknownDirective#
UnknownDirectiveThe letter after % is not a directive.
UnfinishedDirective#
UnfinishedDirectiveThe pattern ends after %, a flag, or a width.
InvalidModifier#
InvalidModifierA : is before a directive other than %z, or a . is before a directive other than %f
and %N.
WidthTooLarge#
WidthTooLargeA width is above 64.
NotAvailable#
NotAvailableThe directive needs a part that the value does not have, such as %H for a PlainDate.
NotReadable#
NotReadableThe directive is %Z, which can be written and cannot be read.
MissingDate#
MissingDateThe pattern does not give a date, and the type needs one.
MissingTime#
MissingTimeThe pattern does not give a time of day, and the type needs one.
MissingOffset#
MissingOffsetThe pattern does not give a UTC offset, and the type needs one.
Implementation Debug for PatternReason#
impl Debug for PatternReasonOperation debug#
effect fn debug(self: &Self, formatter: &mut Formatter) -> ()
! WriterError
? &mut WriterPatternError#
pub struct PatternErrorThe error of a pattern that is known only at run time: why the pattern cannot be used and where.
Field reason#
pub reason: PatternReasonThe cause.
Field offset#
pub offset: usizeThe byte offset of the directive in the pattern. For a missing part it is the length of the pattern.
Implementation Copy for PatternError#
impl Copy for PatternErrorImplementation Debug for PatternError#
impl Debug for PatternErrorOperation debug#
effect fn debug(self: &Self, formatter: &mut Formatter) -> ()
! WriterError
? &mut WriterPatternParts#
pub struct PatternPartsThe parts of a value that directives can write.
Field date#
pub date: boolThe value has a date.
Field time#
pub time: boolThe value has a time of day.
Field offset#
pub offset: boolThe value has a UTC offset.
Field zone#
pub zone: boolThe value has a time zone abbreviation.
Implementation Copy for PatternParts#
impl Copy for PatternPartsPatternKind#
pub enum PatternKindWhat a type needs from a pattern to be read from text.
Date#
DateA date.
Time#
TimeA time of day.
DateTime#
DateTimeA date. The time of day is midnight if the pattern has none.
Instant#
InstantA date, a time of day and a UTC offset, or the seconds from the Unix epoch.
TimeFields#
pub struct TimeFieldsThe fields of a date and time that directives write.
When to use#
Return it from PatternSource.fields to make a type of your own writable with a pattern.
Fields that the type does not have can hold any value, because the directives that read them
are refused for the type.
Field year#
pub year: i32The year.
Field month#
pub month: u8The month, 1 to 12.
Field day#
pub day: u8The day of the month, 1 to 31.
Field hour#
pub hour: u8The hour, 0 to 23.
Field minute#
pub minute: u8The minute, 0 to 59.
Field second#
pub second: u8The second, 0 to 59.
Field nanosecond#
pub nanosecond: u32The nanoseconds in the second.
Field offsetSeconds#
pub offsetSeconds: i32The UTC offset in seconds.
Field abbreviation#
pub abbreviation: [u8; 12]The time zone abbreviation, in the first abbreviationLength bytes.
Field abbreviationLength#
pub abbreviationLength: usizeThe length of the abbreviation.
Implementation Copy for TimeFields#
impl Copy for TimeFieldsImplementation TimeFields#
impl TimeFieldsAssociated function ofDate#
pub fn ofDate(date: PlainDate) -> TimeFieldsReturns the fields of date at midnight UTC.
Method withTime#
pub fn withTime(self: Self, time: PlainTime) -> TimeFieldsReturns the fields with the time of day time.
Method withZone#
pub fn withZone(self: Self, offset: UtcOffset, name: string) -> TimeFieldsReturns the fields with the UTC offset offset and the time zone abbreviation name, of
which the first 12 bytes are kept.
PatternSource#
pub interface PatternSourceA value that a pattern can write.
Details#
It is implemented for PlainDate, PlainTime, PlainDateTime, Instant, which is written
in UTC, and ZonedDateTime.
Operation parts#
static fn parts() -> PatternPartsReturns the parts that the type has. A directive that needs another part is refused.
Operation fields#
fn fields(self: &Self) -> TimeFieldsReturns the fields of the value.
Implementation PatternSource for PlainDate#
impl PatternSource for PlainDateOperation parts#
static fn parts() -> PatternPartsA date only.
Operation fields#
fn fields(self: &Self) -> TimeFieldsReturns the date at midnight.
Implementation PatternSource for PlainTime#
impl PatternSource for PlainTimeOperation parts#
static fn parts() -> PatternPartsA time of day only.
Operation fields#
fn fields(self: &Self) -> TimeFieldsReturns the time of day.
Implementation PatternSource for PlainDateTime#
impl PatternSource for PlainDateTimeOperation parts#
static fn parts() -> PatternPartsA date and a time of day.
Operation fields#
fn fields(self: &Self) -> TimeFieldsReturns the date and the time of day.
Implementation PatternSource for Instant#
impl PatternSource for InstantOperation parts#
static fn parts() -> PatternPartsEvery part: the date and time in UTC, the offset zero and the abbreviation UTC.
Operation fields#
fn fields(self: &Self) -> TimeFieldsReturns the date and time in UTC.
Implementation PatternSource for ZonedDateTime<'z>#
impl<'z> PatternSource for ZonedDateTime<'z>Operation parts#
static fn parts() -> PatternPartsEvery part.
Operation fields#
fn fields(self: &Self) -> TimeFieldsReturns the local date and time, the offset and the abbreviation of the zone.
PatternTarget#
pub interface PatternTargetA type that a pattern can read.
Details#
It is implemented for PlainDate, PlainTime, PlainDateTime and Instant. To read a
ZonedDateTime, read a PlainDateTime and give it a zone with ZonedDateTime.fromLocal.
Operation kind#
static fn kind() -> PatternKindReturns what the type needs from a pattern.
Operation resolve#
fn resolve(parsed: &ParsedFields) -> Result<Self, TimeParseError>Returns the value that the fields name.
Errors#
TimeParseErrorif a part is missing or names no real value.
Implementation PatternTarget for PlainDate#
impl PatternTarget for PlainDateOperation kind#
static fn kind() -> PatternKindA date.
Operation resolve#
fn resolve(parsed: &ParsedFields) -> Result<PlainDate, TimeParseError>Returns the date.
Implementation PatternTarget for PlainTime#
impl PatternTarget for PlainTimeOperation kind#
static fn kind() -> PatternKindA time of day.
Operation resolve#
fn resolve(parsed: &ParsedFields) -> Result<PlainTime, TimeParseError>Returns the time of day.
Implementation PatternTarget for PlainDateTime#
impl PatternTarget for PlainDateTimeOperation kind#
static fn kind() -> PatternKindA date, with a time of day if the pattern has one.
Operation resolve#
fn resolve(parsed: &ParsedFields) -> Result<PlainDateTime, TimeParseError>Returns the date and time.
Implementation PatternTarget for Instant#
impl PatternTarget for InstantOperation kind#
static fn kind() -> PatternKindA date, a time of day and an offset, or the seconds from the Unix epoch.
Operation resolve#
fn resolve(parsed: &ParsedFields) -> Result<Instant, TimeParseError>Returns the instant.
ParsedFields#
pub struct ParsedFieldsWhat a pattern read from a text, before it becomes a value.
When to use#
Get it from TimePattern.parseFields to read a text that has more than one value, such as a
local date and time with its offset, or to accept a text that can leave parts out.
Implementation Copy for ParsedFields#
impl Copy for ParsedFieldsImplementation ParsedFields#
impl ParsedFieldsMethod weekday#
pub fn weekday(self: &Self) -> Option<Weekday>Returns the weekday that the text names, or None if the pattern has no weekday.
Method offset#
pub fn offset(self: &Self) -> Option<UtcOffset>Returns the UTC offset that the text names, or None if the pattern has no %z.
Method date#
pub fn date(self: &Self) -> Result<PlainDate, TimeParseError>Returns the date that the text names.
Details#
The date is the year with the month and the day, or with the day of the year, or with a
week of %U or %W and a weekday, or the ISO 8601 week year with %V and a weekday. A
text with only %s gives the date in UTC.
Errors#
TimeParseReason.MissingDateif the pattern does not give a date.TimeParseReason.OutOfRangeif the date does not exist, or a weekday in the text is not the weekday of the date.
Method time#
pub fn time(self: &Self) -> Result<PlainTime, TimeParseError>Returns the time of day that the text names.
Details#
The hour is %H, or %I with %p; %I without %p is before noon. The minute, the
second and the fraction are 0 if the pattern has none. A text with only %s gives the time
in UTC.
Errors#
TimeParseReason.MissingTimeif the pattern does not give an hour.TimeParseReason.OutOfRangeif the time does not exist, such as hour 24 or second 60.
Method dateTime#
pub fn dateTime(self: &Self) -> Result<PlainDateTime, TimeParseError>Returns the date and time that the text names. The time is midnight if the pattern has no time of day.
Errors#
TimeParseReason.MissingDateif the pattern does not give a date.TimeParseReason.OutOfRangeif the date or the time does not exist.
Method instant#
pub fn instant(self: &Self) -> Result<Instant, TimeParseError>Returns the instant that the text names: the seconds of %s, or the date and time at the
offset of %z.
Errors#
TimeParseReason.MissingDate,MissingTimeorMissingOffsetif the pattern does not give that part and has no%s.TimeParseReason.OutOfRangeif the date or the time does not exist, or the instant is outside the range ofInstant.
TimePattern#
pub struct TimePatternFunctions that write and read dates and times with strftime patterns.
Implementation TimePattern#
impl TimePatternAssociated function write#
pub effect fn write<T: PatternSource>(static pattern: string<'static>, value: &T) -> ()
! WriterError
? &mut WriterWrites value with the constant pattern pattern to the Writer.
Details#
The pattern is checked when the program is compiled. A directive that is not known, or that
needs a part value does not have, is a compile error.
Errors#
WriterErrorif theWriterfails.
Associated function format#
pub effect fn format<T: PatternSource>(static pattern: string<'static>, value: &T) -> String
! OutOfMemoryError
? &mut AllocatorReturns value written with the constant pattern pattern.
Details#
The pattern is checked when the program is compiled, as TimePattern.write checks it.
Errors#
OutOfMemoryErrorif theAllocatorcannot supply the text.
Associated function parse#
pub fn parse<T: PatternTarget>(static pattern: string<'static>, text: string) -> Result<T, TimeParseError>Reads a T from text with the constant pattern pattern.
Details#
The pattern is checked when the program is compiled. A directive that is not known, %Z,
or a pattern that does not give what T needs, such as a PlainDate without a year, is a
compile error.
Errors#
TimeParseReason.UnexpectedEndorUnexpectedCharacteriftextdoes not have the form of the pattern.TimeParseReason.OutOfRangeif a field names no real value, such as month 13 or February 30, or a weekday that is not the weekday of the date.
Associated function parseFields#
pub fn parseFields(static pattern: string<'static>, text: string) -> Result<ParsedFields, TimeParseError>Reads the fields of text with the constant pattern pattern, without making a value.
When to use#
Use it for a text that has more than one value, or parts that a single type does not hold,
and take the values with ParsedFields.date, ParsedFields.time and the others.
Errors#
TimeParseReason.UnexpectedEndorUnexpectedCharacteriftextdoes not have the form of the pattern.TimeParseReason.OutOfRangeif a field is outside its range, such as month 13.
Associated function validate#
pub fn validate<T: PatternSource>(pattern: string) -> Result<(), PatternError>Checks a pattern that is known only at run time, for writing a T.
Errors#
PatternErrorif a directive is malformed or unknown, or needs a part thatTdoes not have.
Associated function formatDynamic#
pub effect fn formatDynamic<T: PatternSource>(pattern: string, value: &T) -> Result<String, PatternError>
! OutOfMemoryError
? &mut AllocatorReturns value written with a pattern that is known only at run time.
Errors#
PatternErroras theResultfailure if a directive is malformed or unknown, or needs a part thatvaluedoes not have.OutOfMemoryErrorif theAllocatorcannot supply the text.
Associated function parseFieldsDynamic#
pub fn parseFieldsDynamic(pattern: string, text: string) -> Result<Result<ParsedFields, TimeParseError>, PatternError>Reads the fields of text with a pattern that is known only at run time.
Details#
The outer Result fails for a pattern that cannot be used, and the inner one for a text
that does not have the form of the pattern.
Errors#
PatternErrorif a directive is malformed or unknown, or is%Z.TimeParseErrorin the innerResult, asTimePattern.parseFieldsreturns it.
Associated function parseDynamic#
pub fn parseDynamic<T: PatternTarget>(pattern: string, text: string) -> Result<Result<T, TimeParseError>, PatternError>Reads a T from text with a pattern that is known only at run time.
Details#
The outer Result fails for a pattern that cannot be used, and the inner one for a text
that does not have the form of the pattern.
Errors#
PatternErrorif a directive is malformed or unknown, or is%Z, or the pattern does not give whatTneeds.TimeParseErrorin the innerResult, asTimePattern.parsereturns it.
Category: Time.
Profiles: aarch64-apple-darwin, aarch64-unknown-linux-gnu, aarch64-unknown-linux-gnu-no-libc, x86_64-unknown-linux-gnu, x86_64-unknown-linux-gnu-no-libc, wasm32-unknown-unknown, wasm32-wasip1, wasm32-wasip2, x86_64-pc-windows-msvc, wasm64-unknown-unknown.