122 lines
2.2 KiB
Markdown
122 lines
2.2 KiB
Markdown
---
|
|
title: "time"
|
|
description: "Time constants and conversion functions"
|
|
weight: 60
|
|
type: "docs"
|
|
---
|
|
|
|
The time module provides time constants and conversion functions.
|
|
|
|
```javascript
|
|
var time = use('time')
|
|
```
|
|
|
|
## Constants
|
|
|
|
| Constant | Value | Description |
|
|
|----------|-------|-------------|
|
|
| `time.second` | 1 | Seconds in a second |
|
|
| `time.minute` | 60 | Seconds in a minute |
|
|
| `time.hour` | 3600 | Seconds in an hour |
|
|
| `time.day` | 86400 | Seconds in a day |
|
|
| `time.week` | 604800 | Seconds in a week |
|
|
| `time.month` | 2629746 | Seconds in a month (30.44 days) |
|
|
| `time.year` | 31556952 | Seconds in a year (365.24 days) |
|
|
|
|
## Getting Current Time
|
|
|
|
### time.number()
|
|
|
|
Get current time as seconds since epoch.
|
|
|
|
```javascript
|
|
var now = time.number() // e.g., 1702656000
|
|
```
|
|
|
|
### time.record()
|
|
|
|
Get current time as a record.
|
|
|
|
```javascript
|
|
var now = time.record()
|
|
// {year: 2024, month: 1, day: 15, hour: 10, minute: 30, second: 45, nanosecond: 123456789}
|
|
```
|
|
|
|
### time.text(format)
|
|
|
|
Get current time as formatted text.
|
|
|
|
```javascript
|
|
time.text() // default format
|
|
time.text("yyyy-MM-dd HH:mm:ss.SSS") // custom format
|
|
```
|
|
|
|
## Converting Time
|
|
|
|
### time.number(text, format, zone)
|
|
|
|
Parse text to timestamp.
|
|
|
|
```javascript
|
|
time.number("2024-01-15", "yyyy-MM-dd")
|
|
```
|
|
|
|
### time.number(record)
|
|
|
|
Convert record to timestamp.
|
|
|
|
```javascript
|
|
time.number({year: 2024, month: 1, day: 15})
|
|
```
|
|
|
|
### time.text(number, format, zone)
|
|
|
|
Format timestamp as text.
|
|
|
|
```javascript
|
|
time.text(1702656000, "yyyy-MM-dd") // "2024-01-15"
|
|
```
|
|
|
|
### time.record(number)
|
|
|
|
Convert timestamp to record.
|
|
|
|
```javascript
|
|
time.record(1702656000)
|
|
// {year: 2024, month: 1, day: 15, ...}
|
|
```
|
|
|
|
## Time Arithmetic
|
|
|
|
```javascript
|
|
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
|
|
|
|
```javascript
|
|
var time = use('time')
|
|
|
|
// Measure execution time
|
|
var start = time.number()
|
|
// ... do work ...
|
|
var elapsed = time.number() - start
|
|
log.console(`Took ${elapsed} seconds`)
|
|
|
|
// Schedule for tomorrow
|
|
var tomorrow = time.number() + time.day
|
|
log.console(`Tomorrow: ${time.text(tomorrow, "yyyy-MM-dd")}`)
|
|
```
|