Add Date type and database release docs
This commit is contained in:
1 parent
14dc73db3e
commit
b3be908242
19 files changed
+928
-106
No files matched your search
@@ -81,7 +81,7 @@ Sources: `lynglib/src/commonMain/kotlin/net/sergeych/lyng/Script.kt`, `lynglib/s
|
||||
- `import lyng.serialization`
|
||||
- `Lynon` serialization utilities.
|
||||
- `import lyng.time`
|
||||
- `Instant`, `DateTime`, `Duration`, and module `delay`.
|
||||
- `Instant`, `Date`, `DateTime`, `Duration`, and module `delay`.
|
||||
|
||||
## 6. Optional (lyngio) Modules
|
||||
Requires installing `lyngio` into the import manager from host code.
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
### lyng.io.db — SQL database access for Lyng scripts
|
||||
|
||||
This module provides the portable SQL database contract for Lyng. The first shipped provider is SQLite via `lyng.io.db.sqlite`.
|
||||
|
||||
> **Note:** `lyngio` is a separate library module. It must be explicitly added as a dependency to your host application and initialized in your Lyng scopes.
|
||||
|
||||
---
|
||||
|
||||
#### Install the module into a Lyng session
|
||||
|
||||
For SQLite-backed database access, install both the generic DB module and the SQLite provider:
|
||||
|
||||
```kotlin
|
||||
import net.sergeych.lyng.EvalSession
|
||||
import net.sergeych.lyng.Scope
|
||||
import net.sergeych.lyng.io.db.createDbModule
|
||||
import net.sergeych.lyng.io.db.sqlite.createSqliteModule
|
||||
|
||||
suspend fun bootstrapDb() {
|
||||
val session = EvalSession()
|
||||
val scope: Scope = session.getScope()
|
||||
createDbModule(scope)
|
||||
createSqliteModule(scope)
|
||||
session.eval("""
|
||||
import lyng.io.db
|
||||
import lyng.io.db.sqlite
|
||||
""".trimIndent())
|
||||
}
|
||||
```
|
||||
|
||||
`createSqliteModule(...)` also registers the `sqlite:` scheme for generic `openDatabase(...)`.
|
||||
|
||||
---
|
||||
|
||||
#### Using from Lyng scripts
|
||||
|
||||
Typed SQLite open helper:
|
||||
|
||||
```lyng
|
||||
import lyng.io.db.sqlite
|
||||
|
||||
val db = openSqlite(":memory:")
|
||||
|
||||
val userCount = db.transaction { tx ->
|
||||
tx.execute("create table user(id integer primary key autoincrement, name text not null)")
|
||||
tx.execute("insert into user(name) values(?)", "Ada")
|
||||
tx.execute("insert into user(name) values(?)", "Linus")
|
||||
tx.select("select count(*) as count from user").toList()[0]["count"]
|
||||
}
|
||||
|
||||
assertEquals(2, userCount)
|
||||
```
|
||||
|
||||
Generic provider-based open:
|
||||
|
||||
```lyng
|
||||
import lyng.io.db
|
||||
import lyng.io.db.sqlite
|
||||
|
||||
val db = openDatabase(
|
||||
"sqlite:./app.db",
|
||||
Map(
|
||||
"foreignKeys" => true,
|
||||
"busyTimeoutMillis" => 5000
|
||||
)
|
||||
)
|
||||
```
|
||||
|
||||
Nested transactions use real savepoint semantics:
|
||||
|
||||
```lyng
|
||||
import lyng.io.db
|
||||
import lyng.io.db.sqlite
|
||||
|
||||
val db = openSqlite(":memory:")
|
||||
|
||||
db.transaction { tx ->
|
||||
tx.execute("create table item(id integer primary key autoincrement, name text not null)")
|
||||
tx.execute("insert into item(name) values(?)", "outer")
|
||||
|
||||
try {
|
||||
tx.transaction { inner ->
|
||||
inner.execute("insert into item(name) values(?)", "inner")
|
||||
throw IllegalStateException("rollback nested")
|
||||
}
|
||||
} catch (_: IllegalStateException) {
|
||||
}
|
||||
|
||||
assertEquals(1, tx.select("select count(*) as count from item").toList()[0]["count"])
|
||||
}
|
||||
```
|
||||
|
||||
Intentional rollback without treating it as a backend failure:
|
||||
|
||||
```lyng
|
||||
import lyng.io.db
|
||||
import lyng.io.db.sqlite
|
||||
|
||||
val db = openSqlite(":memory:")
|
||||
|
||||
assertThrows(RollbackException) {
|
||||
db.transaction { tx ->
|
||||
tx.execute("create table item(id integer primary key autoincrement, name text not null)")
|
||||
tx.execute("insert into item(name) values(?)", "temporary")
|
||||
throw RollbackException("stop here")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### Portable API
|
||||
|
||||
##### `Database`
|
||||
|
||||
- `transaction(block)` — opens a transaction, commits on normal exit, rolls back on uncaught failure.
|
||||
|
||||
##### `SqlTransaction`
|
||||
|
||||
- `select(clause, params...)` — execute a statement whose primary result is a row set.
|
||||
- `execute(clause, params...)` — execute a side-effect statement and return `ExecutionResult`.
|
||||
- `transaction(block)` — nested transaction with real savepoint semantics.
|
||||
|
||||
##### `ResultSet`
|
||||
|
||||
- `columns` — positional `SqlColumn` metadata, available before iteration.
|
||||
- `size()` — result row count.
|
||||
- `isEmpty()` — fast emptiness check where possible.
|
||||
- `iterator()` / `toList()` — normal row iteration.
|
||||
|
||||
##### `SqlRow`
|
||||
|
||||
- `row[index]` — zero-based positional access.
|
||||
- `row["columnName"]` — case-insensitive lookup by output column label.
|
||||
|
||||
Name-based access fails with `SqlUsageException` if the name is missing or ambiguous.
|
||||
|
||||
##### `ExecutionResult`
|
||||
|
||||
- `affectedRowsCount`
|
||||
- `getGeneratedKeys()`
|
||||
|
||||
Statements that return rows directly, such as `... returning ...`, should use `select(...)`, not `execute(...)`.
|
||||
|
||||
---
|
||||
|
||||
#### Value mapping
|
||||
|
||||
Portable bind values:
|
||||
|
||||
- `null`
|
||||
- `Bool`
|
||||
- `Int`, `Double`, `Decimal`
|
||||
- `String`
|
||||
- `Buffer`
|
||||
- `Date`, `DateTime`, `Instant`
|
||||
|
||||
Unsupported parameter values fail with `SqlUsageException`.
|
||||
|
||||
Portable result metadata categories:
|
||||
|
||||
- `Binary`
|
||||
- `String`
|
||||
- `Int`
|
||||
- `Double`
|
||||
- `Decimal`
|
||||
- `Bool`
|
||||
- `Date`
|
||||
- `DateTime`
|
||||
- `Instant`
|
||||
|
||||
For temporal types, see [time functions](time.md).
|
||||
|
||||
---
|
||||
|
||||
#### SQLite provider
|
||||
|
||||
`lyng.io.db.sqlite` currently provides the first concrete backend.
|
||||
|
||||
Typed helper:
|
||||
|
||||
```lyng
|
||||
openSqlite(
|
||||
path: String,
|
||||
readOnly: Bool = false,
|
||||
createIfMissing: Bool = true,
|
||||
foreignKeys: Bool = true,
|
||||
busyTimeoutMillis: Int = 5000
|
||||
): Database
|
||||
```
|
||||
|
||||
Accepted generic URL forms:
|
||||
|
||||
- `sqlite::memory:`
|
||||
- `sqlite:relative/path.db`
|
||||
- `sqlite:/absolute/path.db`
|
||||
|
||||
Supported `openDatabase(..., extraParams)` keys for SQLite:
|
||||
|
||||
- `readOnly: Bool`
|
||||
- `createIfMissing: Bool`
|
||||
- `foreignKeys: Bool`
|
||||
- `busyTimeoutMillis: Int`
|
||||
|
||||
SQLite write/read policy in v1:
|
||||
|
||||
- `Bool` writes as `0` / `1`
|
||||
- `Decimal` writes as canonical text
|
||||
- `Date` writes as `YYYY-MM-DD`
|
||||
- `DateTime` writes as ISO local timestamp text without timezone
|
||||
- `Instant` writes as ISO UTC timestamp text with explicit timezone marker
|
||||
- `TIME*` values stay `String`
|
||||
- `TIMESTAMP` / `DATETIME` reject timezone-bearing stored text
|
||||
|
||||
Open-time validation failures:
|
||||
|
||||
- malformed URL or bad option shape -> `IllegalArgumentException`
|
||||
- runtime open failure -> `DatabaseException`
|
||||
|
||||
---
|
||||
|
||||
#### Lifetime rules
|
||||
|
||||
Result sets and rows are valid only while their owning transaction is active.
|
||||
|
||||
This means:
|
||||
|
||||
- do not keep `ResultSet` or `SqlRow` objects after the transaction block returns
|
||||
- copy the values you need into ordinary Lyng objects inside the transaction
|
||||
|
||||
The same lifetime rule applies to generated keys returned by `ExecutionResult.getGeneratedKeys()`.
|
||||
|
||||
---
|
||||
|
||||
#### Platform support
|
||||
|
||||
- `lyng.io.db` — generic contract, available when host code installs it
|
||||
- `lyng.io.db.sqlite` — implemented on JVM and Linux Native in the current release tree
|
||||
|
||||
For the broader I/O overview, see [lyngio overview](lyngio.md).
|
||||
+20
-10
@@ -12,6 +12,7 @@
|
||||
|
||||
#### Included Modules
|
||||
|
||||
- **[lyng.io.db](lyng.io.db.md):** Portable SQL database access. Provides `Database`, `SqlTransaction`, `ResultSet`, and SQLite support through `lyng.io.db.sqlite`.
|
||||
- **[lyng.io.fs](lyng.io.fs.md):** Async filesystem access. Provides the `Path` class for file/directory operations, streaming, and globbing.
|
||||
- **[lyng.io.process](lyng.io.process.md):** External process execution and shell commands. Provides `Process`, `RunningProcess`, and `Platform` information.
|
||||
- **[lyng.io.console](lyng.io.console.md):** Rich console/TTY access. Provides `Console` capability detection, geometry, output, and iterable events.
|
||||
@@ -43,6 +44,8 @@ To use `lyngio` modules in your scripts, you must install them into your Lyng sc
|
||||
|
||||
```kotlin
|
||||
import net.sergeych.lyng.EvalSession
|
||||
import net.sergeych.lyng.io.db.createDbModule
|
||||
import net.sergeych.lyng.io.db.sqlite.createSqliteModule
|
||||
import net.sergeych.lyng.io.fs.createFs
|
||||
import net.sergeych.lyng.io.process.createProcessModule
|
||||
import net.sergeych.lyng.io.console.createConsoleModule
|
||||
@@ -61,6 +64,8 @@ suspend fun runMyScript() {
|
||||
val scope = session.getScope()
|
||||
|
||||
// Install modules with policies
|
||||
createDbModule(scope)
|
||||
createSqliteModule(scope)
|
||||
createFs(PermitAllAccessPolicy, scope)
|
||||
createProcessModule(PermitAllProcessAccessPolicy, scope)
|
||||
createConsoleModule(PermitAllConsoleAccessPolicy, scope)
|
||||
@@ -70,6 +75,8 @@ suspend fun runMyScript() {
|
||||
|
||||
// Now scripts can import them
|
||||
session.eval("""
|
||||
import lyng.io.db
|
||||
import lyng.io.db.sqlite
|
||||
import lyng.io.fs
|
||||
import lyng.io.process
|
||||
import lyng.io.console
|
||||
@@ -77,6 +84,7 @@ suspend fun runMyScript() {
|
||||
import lyng.io.net
|
||||
import lyng.io.ws
|
||||
|
||||
println("SQLite available: " + (openSqlite(":memory:") != null))
|
||||
println("Working dir: " + Path(".").readUtf8())
|
||||
println("OS: " + Platform.details().name)
|
||||
println("TTY: " + Console.isTty())
|
||||
@@ -94,6 +102,7 @@ suspend fun runMyScript() {
|
||||
`lyngio` is built with a "Secure by Default" philosophy. Every I/O or process operation is checked against a policy.
|
||||
|
||||
- **Filesystem Security:** Implement `FsAccessPolicy` to restrict access to specific paths or operations (e.g., read-only access to a sandbox directory).
|
||||
- **Database Installation:** Database access is still explicit-capability style. The host must install `lyng.io.db` and at least one provider such as `lyng.io.db.sqlite`; otherwise scripts cannot open databases.
|
||||
- **Process Security:** Implement `ProcessAccessPolicy` to restrict which executables can be run or to disable shell execution entirely.
|
||||
- **Console Security:** Implement `ConsoleAccessPolicy` to control output writes, event reads, and raw mode switching.
|
||||
- **HTTP Security:** Implement `HttpAccessPolicy` to restrict which requests scripts may send.
|
||||
@@ -101,6 +110,7 @@ suspend fun runMyScript() {
|
||||
- **WebSocket Security:** Implement `WsAccessPolicy` to restrict websocket connects and message flow.
|
||||
|
||||
For more details, see the specific module documentation:
|
||||
- [Database Module Details](lyng.io.db.md)
|
||||
- [Filesystem Security Details](lyng.io.fs.md#access-policy-security)
|
||||
- [Process Security Details](lyng.io.process.md#security-policy)
|
||||
- [Console Module Details](lyng.io.console.md)
|
||||
@@ -112,16 +122,16 @@ For more details, see the specific module documentation:
|
||||
|
||||
#### Platform Support Overview
|
||||
|
||||
| Platform | lyng.io.fs | lyng.io.process | lyng.io.console | lyng.io.http | lyng.io.ws | lyng.io.net |
|
||||
| :--- | :---: | :---: | :---: | :---: | :---: | :---: |
|
||||
| **JVM** | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| **Linux Native** | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| **Apple Native** | ✅ | ✅ | ✅ | ✅ | ✅ | ⚠️ |
|
||||
| **Windows Native** | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ |
|
||||
| **Android** | ✅ | ❌ | ⚠️ | ✅ | ✅ | ✅ |
|
||||
| **JS / Node** | ✅ | ❌ | ⚠️ | ✅ | ✅ | ✅ |
|
||||
| **JS / Browser** | ✅ (in-memory) | ❌ | ⚠️ | ✅ | ✅ | ❌ |
|
||||
| **Wasm** | ✅ (in-memory) | ❌ | ⚠️ | ❌ | ❌ | ❌ |
|
||||
| Platform | lyng.io.db/sqlite | lyng.io.fs | lyng.io.process | lyng.io.console | lyng.io.http | lyng.io.ws | lyng.io.net |
|
||||
| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
|
||||
| **JVM** | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| **Linux Native** | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| **Apple Native** | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ⚠️ |
|
||||
| **Windows Native** | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ |
|
||||
| **Android** | ⚠️ | ✅ | ❌ | ⚠️ | ✅ | ✅ | ✅ |
|
||||
| **JS / Node** | ❌ | ✅ | ❌ | ⚠️ | ✅ | ✅ | ✅ |
|
||||
| **JS / Browser** | ❌ | ✅ (in-memory) | ❌ | ⚠️ | ✅ | ✅ | ❌ |
|
||||
| **Wasm** | ❌ | ✅ (in-memory) | ❌ | ⚠️ | ❌ | ❌ | ❌ |
|
||||
|
||||
Legend:
|
||||
- `✅` supported
|
||||
|
||||
+122
-63
@@ -1,74 +1,135 @@
|
||||
# Lyng time functions
|
||||
|
||||
Lyng date and time support requires importing `lyng.time` packages. Lyng uses simple yet modern time object models:
|
||||
Lyng date and time support requires importing `lyng.time`. The module provides four related types:
|
||||
|
||||
- `Instant` class for absolute time stamps with platform-dependent resolution.
|
||||
- `DateTime` class for calendar-aware points in time within a specific time zone.
|
||||
- `Duration` to represent amount of time not depending on the calendar (e.g., milliseconds, seconds).
|
||||
- `Instant` for absolute timestamps.
|
||||
- `Date` for calendar dates without time-of-day or timezone.
|
||||
- `DateTime` for calendar-aware points in time in a specific timezone.
|
||||
- `Duration` for absolute elapsed time.
|
||||
|
||||
## Time instant: `Instant`
|
||||
|
||||
Represent some moment of time not depending on the calendar. It is similar to `TIMESTAMP` in SQL or `Instant` in Kotlin.
|
||||
`Instant` represents some moment of time independently of the calendar. It is similar to SQL `TIMESTAMP`
|
||||
or Kotlin `Instant`.
|
||||
|
||||
### Constructing and converting
|
||||
|
||||
import lyng.time
|
||||
|
||||
// default constructor returns time now:
|
||||
val t1 = Instant()
|
||||
|
||||
// constructing from a number is treated as seconds since unix epoch:
|
||||
val t2 = Instant(1704110400) // 2024-01-01T12:00:00Z
|
||||
|
||||
// from RFC3339 string:
|
||||
val t2 = Instant(1704110400)
|
||||
val t3 = Instant("2024-01-01T12:00:00.123456Z")
|
||||
|
||||
// truncation:
|
||||
val t4 = t3.truncateToMinute
|
||||
assertEquals(t4.toRFC3339(), "2024-01-01T12:00:00Z")
|
||||
|
||||
// to localized DateTime (uses system default TZ if not specified):
|
||||
|
||||
val t4 = t3.truncateToMinute()
|
||||
assertEquals("2024-01-01T12:00:00Z", t4.toRFC3339())
|
||||
|
||||
val dt = t3.toDateTime("+02:00")
|
||||
assertEquals(dt.hour, 14)
|
||||
assertEquals(14, dt.hour)
|
||||
|
||||
val d = t3.toDate("Z")
|
||||
assertEquals(Date(2024, 1, 1), d)
|
||||
|
||||
### Instant members
|
||||
|
||||
| member | description |
|
||||
|--------------------------------|---------------------------------------------------------|
|
||||
| epochSeconds: Real | positive or negative offset in seconds since Unix epoch |
|
||||
| epochWholeSeconds: Int | same, but in _whole seconds_. Slightly faster |
|
||||
| nanosecondsOfSecond: Int | offset from epochWholeSeconds in nanos |
|
||||
| isDistantFuture: Bool | true if it `Instant.distantFuture` |
|
||||
| isDistantPast: Bool | true if it `Instant.distantPast` |
|
||||
| truncateToMinute: Instant | create new instance truncated to minute |
|
||||
| truncateToSecond: Instant | create new instance truncated to second |
|
||||
| truncateToMillisecond: Instant | truncate new instance to millisecond |
|
||||
| truncateToMicrosecond: Instant | truncate new instance to microsecond |
|
||||
| toRFC3339(): String | format as RFC3339 string (UTC) |
|
||||
| toDateTime(tz?): DateTime | localize to a TimeZone (ID string or offset seconds) |
|
||||
| member | description |
|
||||
|--------------------------------|------------------------------------------------------|
|
||||
| epochSeconds: Real | offset in seconds since Unix epoch |
|
||||
| epochWholeSeconds: Int | whole seconds since Unix epoch |
|
||||
| nanosecondsOfSecond: Int | nanoseconds within the current second |
|
||||
| isDistantFuture: Bool | true if it is `Instant.distantFuture` |
|
||||
| isDistantPast: Bool | true if it is `Instant.distantPast` |
|
||||
| truncateToMinute(): Instant | truncate to minute precision |
|
||||
| truncateToSecond(): Instant | truncate to second precision |
|
||||
| truncateToMillisecond(): Instant | truncate to millisecond precision |
|
||||
| truncateToMicrosecond(): Instant | truncate to microsecond precision |
|
||||
| toRFC3339(): String | format as RFC3339 string in UTC |
|
||||
| toDateTime(tz?): DateTime | localize to a timezone |
|
||||
| toDate(tz?): Date | convert to a calendar date in a timezone |
|
||||
|
||||
## Calendar time: `DateTime`
|
||||
## Calendar date: `Date`
|
||||
|
||||
`DateTime` represents a point in time in a specific timezone. It provides access to calendar components like year,
|
||||
month, and day.
|
||||
`Date` represents a pure calendar date. It has no time-of-day and no attached timezone. Use it for values
|
||||
like birthdays, due dates, invoice dates, and SQL `DATE` columns.
|
||||
|
||||
### Constructing
|
||||
|
||||
import lyng.time
|
||||
|
||||
val today = Date()
|
||||
val d1 = Date(2026, 4, 15)
|
||||
val d2 = Date("2024-02-29")
|
||||
val d3 = Date.parseIso("2024-02-29")
|
||||
val d4 = Date(DateTime(2024, 5, 20, 15, 30, 45, "+02:00"))
|
||||
val d5 = Date(Instant("2024-01-01T23:30:00Z"), "+02:00")
|
||||
|
||||
### Date members
|
||||
|
||||
| member | description |
|
||||
|--------------------------------|------------------------------------------------------------|
|
||||
| year: Int | year component |
|
||||
| month: Int | month component (1..12) |
|
||||
| day: Int | day of month (alias `dayOfMonth`) |
|
||||
| dayOfWeek: Int | day of week (1=Monday, 7=Sunday) |
|
||||
| dayOfYear: Int | day of year (1..365/366) |
|
||||
| isLeapYear: Bool | whether this date is in a leap year |
|
||||
| lengthOfMonth: Int | number of days in this month |
|
||||
| lengthOfYear: Int | 365 or 366 |
|
||||
| toIsoString(): String | ISO `YYYY-MM-DD` string |
|
||||
| toSortableString(): String | alias to `toIsoString()` |
|
||||
| toDateTime(tz="Z"): DateTime | start-of-day `DateTime` in the specified timezone |
|
||||
| atStartOfDay(tz="Z"): DateTime | alias to `toDateTime()` |
|
||||
| addDays(n): Date | add or subtract calendar days |
|
||||
| addMonths(n): Date | add or subtract months, normalizing end-of-month |
|
||||
| addYears(n): Date | add or subtract years |
|
||||
| daysUntil(other): Int | calendar days until `other` |
|
||||
| daysSince(other): Int | calendar days since `other` |
|
||||
| static today(tz?): Date | today in the specified timezone |
|
||||
| static parseIso(s): Date | parse ISO `YYYY-MM-DD` |
|
||||
|
||||
### Date arithmetic
|
||||
|
||||
`Date` supports only whole-day arithmetic. This is deliberate: calendar dates should not silently accept
|
||||
sub-day durations.
|
||||
|
||||
import lyng.time
|
||||
|
||||
val d1 = Date(2026, 4, 15)
|
||||
val d2 = d1.addDays(10)
|
||||
|
||||
assertEquals(Date(2026, 4, 25), d2)
|
||||
assertEquals(Date(2026, 4, 18), d1 + 3.days)
|
||||
assertEquals(Date(2026, 4, 12), d1 - 3.days)
|
||||
assertEquals(10, d1.daysUntil(d2))
|
||||
assertEquals(10, d2.daysSince(d1))
|
||||
assertEquals(10, d2 - d1)
|
||||
|
||||
### Date conversions
|
||||
|
||||
import lyng.time
|
||||
|
||||
val i = Instant("2024-01-01T23:30:00Z")
|
||||
assertEquals(Date(2024, 1, 1), i.toDate("Z"))
|
||||
assertEquals(Date(2024, 1, 2), i.toDate("+02:00"))
|
||||
|
||||
val dt = DateTime(2024, 5, 20, 15, 30, 45, "+02:00")
|
||||
assertEquals(Date(2024, 5, 20), dt.date)
|
||||
assertEquals(Date(2024, 5, 20), dt.toDate())
|
||||
assertEquals(DateTime(2024, 5, 20, 0, 0, 0, "Z"), Date(2024, 5, 20).toDateTime("Z"))
|
||||
assertEquals(DateTime(2024, 5, 20, 0, 0, 0, "+02:00"), Date(2024, 5, 20).atStartOfDay("+02:00"))
|
||||
|
||||
## Calendar time: `DateTime`
|
||||
|
||||
`DateTime` represents a point in time in a specific timezone. It provides access to calendar components
|
||||
such as year, month, day, and hour.
|
||||
|
||||
### Constructing
|
||||
|
||||
import lyng.time
|
||||
|
||||
// Current time in system default timezone
|
||||
val now = DateTime.now()
|
||||
|
||||
// Specific timezone
|
||||
val offsetTime = DateTime.now("+02:00")
|
||||
|
||||
// From Instant
|
||||
val dt = Instant().toDateTime("Z")
|
||||
|
||||
// By components (year, month, day, hour=0, minute=0, second=0, timeZone="UTC")
|
||||
val dt2 = DateTime(2024, 1, 1, 12, 0, 0, "Z")
|
||||
|
||||
// From RFC3339 string
|
||||
val dt3 = DateTime.parseRFC3339("2024-01-01T12:00:00+02:00")
|
||||
|
||||
### DateTime members
|
||||
@@ -83,7 +144,9 @@ month, and day.
|
||||
| second: Int | second component (0..59) |
|
||||
| dayOfWeek: Int | day of week (1=Monday, 7=Sunday) |
|
||||
| timeZone: String | timezone ID string |
|
||||
| date: Date | calendar date component |
|
||||
| toInstant(): Instant | convert back to absolute Instant |
|
||||
| toDate(): Date | extract the calendar date in this timezone |
|
||||
| toUTC(): DateTime | shortcut to convert to UTC |
|
||||
| toTimeZone(tz): DateTime | convert to another timezone |
|
||||
| addMonths(n): DateTime | add/subtract months (normalizes end of month) |
|
||||
@@ -96,28 +159,27 @@ month, and day.
|
||||
|
||||
`DateTime` handles calendar arithmetic correctly:
|
||||
|
||||
import lyng.time
|
||||
|
||||
val leapDay = Instant("2024-02-29T12:00:00Z").toDateTime("Z")
|
||||
val nextYear = leapDay.addYears(1)
|
||||
assertEquals(nextYear.day, 28) // Feb 29, 2024 -> Feb 28, 2025
|
||||
assertEquals(28, nextYear.day)
|
||||
|
||||
# `Duration` class
|
||||
|
||||
Represent absolute time distance between two `Instant`.
|
||||
`Duration` represents absolute elapsed time between two instants.
|
||||
|
||||
import lyng.time
|
||||
|
||||
val t1 = Instant()
|
||||
|
||||
// yes we can delay to period, and it is not blocking. is suspends!
|
||||
delay(1.millisecond)
|
||||
|
||||
val t2 = Instant()
|
||||
// be suspend, so actual time may vary:
|
||||
assert( t2 - t1 >= 1.millisecond)
|
||||
assert( t2 - t1 < 100.millisecond)
|
||||
|
||||
assert(t2 - t1 >= 1.millisecond)
|
||||
assert(t2 - t1 < 100.millisecond)
|
||||
>>> void
|
||||
|
||||
Duration can be converted from numbers, like `5.minutes` and so on. Extensions are created for
|
||||
`Int` and `Real`, so for n as Real or Int it is possible to create durations::
|
||||
Duration values can be created from numbers using extensions on `Int` and `Real`:
|
||||
|
||||
- `n.millisecond`, `n.milliseconds`
|
||||
- `n.second`, `n.seconds`
|
||||
@@ -125,10 +187,9 @@ Duration can be converted from numbers, like `5.minutes` and so on. Extensions a
|
||||
- `n.hour`, `n.hours`
|
||||
- `n.day`, `n.days`
|
||||
|
||||
The bigger time units like months or years are calendar-dependent and can't be used with `Duration`.
|
||||
Larger units like months or years are calendar-dependent and are intentionally not part of `Duration`.
|
||||
|
||||
Each duration instance can be converted to number of any of these time units, as `Real` number, if `d` is a `Duration`
|
||||
instance:
|
||||
Each duration instance can be converted to numbers in these units:
|
||||
|
||||
- `d.microseconds`
|
||||
- `d.milliseconds`
|
||||
@@ -137,18 +198,16 @@ instance:
|
||||
- `d.hours`
|
||||
- `d.days`
|
||||
|
||||
for example
|
||||
Example:
|
||||
|
||||
import lyng.time
|
||||
assertEquals( 60, 1.minute.seconds )
|
||||
assertEquals( 10.milliseconds, 0.01.seconds )
|
||||
|
||||
assertEquals(60, 1.minute.seconds)
|
||||
assertEquals(10.milliseconds, 0.01.seconds)
|
||||
>>> void
|
||||
|
||||
# Utility functions
|
||||
|
||||
## delay(duration: Duration)
|
||||
|
||||
Suspends current coroutine for at least the specified duration.
|
||||
|
||||
## `delay(duration: Duration)`
|
||||
|
||||
Suspends the current coroutine for at least the specified duration.
|
||||
+3
-2
@@ -18,8 +18,9 @@ For a programmer-focused migration summary across 1.5.x, see `docs/whats_new_1_5
|
||||
- Descending ranges and loops with `downTo` / `downUntil`
|
||||
- String interpolation with `$name` and `${expr}`
|
||||
- Decimal arithmetic, matrices/vectors, and complex numbers
|
||||
- Calendar `Date` support in `lyng.time`
|
||||
- Immutable collections and opt-in `ObservableList`
|
||||
- Rich `lyngio` modules for console, HTTP, WebSocket, TCP, and UDP
|
||||
- Rich `lyngio` modules for SQLite databases, console, HTTP, WebSocket, TCP, and UDP
|
||||
- CLI improvements including the built-in formatter `lyng fmt`
|
||||
- Better IDE support and stronger docs around the released feature set
|
||||
|
||||
@@ -579,7 +580,7 @@ ws.close()
|
||||
|
||||
These modules are capability-gated and host-installed, keeping Lyng safe by default while making networked scripts practical when enabled.
|
||||
|
||||
See [lyngio overview](lyngio.md), [lyng.io.http](lyng.io.http.md), [lyng.io.ws](lyng.io.ws.md), and [lyng.io.net](lyng.io.net.md).
|
||||
See [lyngio overview](lyngio.md), [lyng.io.db](lyng.io.db.md), [lyng.io.http](lyng.io.http.md), [lyng.io.ws](lyng.io.ws.md), and [lyng.io.net](lyng.io.net.md).
|
||||
|
||||
### CLI: Formatting Command
|
||||
A new `fmt` subcommand has been added to the Lyng CLI.
|
||||
|
||||
Reference in new issue
Block a user