@gitlon/time
v0.1.1
Published
dayjs wrapper for gitlon
Downloads
73
Readme
@gitlon/time
Gitlon 时间包。内部直接转发 dayjs,不包装实例、不修改默认配置。
import time from '@gitlon/time'安装
pnpm add @gitlon/timedayjs 已作为运行时依赖安装。
基础用法
import time from '@gitlon/time'
const now = time()
const createdAt = time('2026-09-15 10:30:00')
createdAt.format('YYYY-MM-DD') // '2026-09-15'
createdAt.add(1, 'day').format() // 返回新 Dayjs 实例
createdAt.startOf('month') // 当月开始时间
createdAt.isBefore(now) // boolean
createdAt.toDate() // Date
createdAt.valueOf() // 毫秒时间戳Dayjs 实例不可变。add、subtract、set 等操作返回新实例,不修改原值。
类型
@gitlon/time 转发 dayjs 的公开类型:
import time, {
type ConfigType,
type Dayjs,
type ManipulateType,
type OpUnitType,
} from '@gitlon/time'
function toDateText(value: ConfigType): string {
const date: Dayjs = time(value)
return date.isValid() ? date.format('YYYY-MM-DD') : ''
}
function add(value: Dayjs, amount: number, unit: ManipulateType): Dayjs {
return value.add(amount, unit)
}
const unit: OpUnitType = 'week'
console.log(time().startOf(unit))常用输入类型:
type ConfigType = string | number | Date | Dayjs | null | undefined最终类型以当前安装的 dayjs 版本为准。
常用 API
| API | 返回值 | 说明 |
| --- | --- | --- |
| time() | Dayjs | 当前时间 |
| time(value) | Dayjs | 解析字符串、时间戳、Date 或 Dayjs |
| time.unix(seconds) | Dayjs | 解析秒级 Unix 时间戳 |
| .format(pattern) | string | 格式化时间 |
| .isValid() | boolean | 是否为有效时间 |
| .add() / .subtract() | Dayjs | 加减时间 |
| .startOf() / .endOf() | Dayjs | 时间单位起止点 |
| .diff() | number | 计算时间差 |
| .toDate() | Date | 转为原生日期 |
| .toISOString() | string | 转为 ISO 字符串 |
| .valueOf() | number | 获取毫秒时间戳 |
插件
本包只导出 dayjs 主入口,不转发 dayjs/plugin/* 子路径。使用插件时,业务项目需要直接安装 dayjs:
pnpm add dayjs然后在应用入口统一扩展:
import time from '@gitlon/time'
import relativeTime from 'dayjs/plugin/relativeTime'
import utc from 'dayjs/plugin/utc'
time.extend(relativeTime)
time.extend(utc)
console.log(time().subtract(1, 'day').fromNow())
console.log(time().utc().format())Locale
Locale 文件同样来自 dayjs:
import time from '@gitlon/time'
import 'dayjs/locale/zh-cn'
time.locale('zh-cn')
console.log(time('2026-09-15').format('dddd'))从 gitlon 使用
gitlon 主包会聚合命名导出,但不会聚合子包默认导出。创建时间实例时仍应直接导入:
import time from '@gitlon/time'类型可从主包导入:
import type { ConfigType, Dayjs } from 'gitlon'注意事项
- 不默认加载 UTC、时区、相对时间等插件。
- 不修改全局 locale。
- 日期解析、格式字符、插件能力均遵循 dayjs 行为。
- 建议在应用入口集中执行
time.extend()和time.locale()。
