时间格式
IBest-ORM 支持配置时间戳字段的格式,可以根据需求选择不同的时间格式。
支持的格式
| 格式 | 示例 | 说明 |
|---|---|---|
datetime | 2024-01-01 12:00:00 | 默认格式,日期时间 |
date | 2024-01-01 | 仅日期 |
time | 12:00:00 | 仅时间 |
timestamp | 1704067200000 | Unix 时间戳(毫秒) |
iso | 2024-01-01T12:00:00.000Z | ISO 8601 格式 |
设置时间格式
ts
import { setTimeFormat, getTimeFormat } from '@ibestservices/ibest-orm';
// 设置全局时间格式
setTimeFormat('datetime'); // 默认
setTimeFormat('iso'); // ISO 格式
setTimeFormat('timestamp'); // 时间戳
// 获取当前时间格式
const format = getTimeFormat();
console.log('当前格式:', format);使用示例
datetime 格式(默认)
ts
setTimeFormat('datetime');
@Table()
class Article {
@PrimaryKey()
id?: number;
@CreatedAt()
createdAt?: string; // 2024-01-01 12:00:00
}ISO 格式
ts
setTimeFormat('iso');
@Table()
class Article {
@PrimaryKey()
id?: number;
@CreatedAt()
createdAt?: string; // 2024-01-01T12:00:00.000Z
}时间戳格式
ts
setTimeFormat('timestamp');
@Table()
class Article {
@PrimaryKey()
id?: number;
@CreatedAt()
createdAt?: string; // 1704067200000
}自动时间戳
配合 @CreatedAt 和 @UpdatedAt 装饰器使用:
ts
import { Table, Column, PrimaryKey, CreatedAt, UpdatedAt, setTimeFormat } from '@ibestservices/ibest-orm';
// 设置时间格式
setTimeFormat('datetime');
@Table()
class Post {
@PrimaryKey()
id?: number;
@Column()
title?: string;
@CreatedAt()
createdAt?: string; // 插入时自动填充
@UpdatedAt()
updatedAt?: string; // 插入和更新时自动填充
}
const orm = getORM();
// 插入记录
const post = new Post();
post.title = '测试文章';
orm.insert(post);
// createdAt 和 updatedAt 自动设置为 '2024-01-01 12:00:00' 格式
// 更新记录
post.title = '更新后的标题';
orm.save(post);
// updatedAt 自动更新格式化工具
IBest-ORM 提供了 formatDate 工具函数:
ts
import { formatDate } from '@ibestservices/ibest-orm';
const now = new Date();
// 使用当前配置的格式
const formatted = formatDate(now);
// 指定格式
const datetime = formatDate(now, 'datetime'); // 2024-01-01 12:00:00
const iso = formatDate(now, 'iso'); // 2024-01-01T12:00:00.000Z
const timestamp = formatDate(now, 'timestamp'); // 1704067200000最佳实践
- 统一格式:在应用初始化时设置统一的时间格式
- 考虑时区:
datetime格式使用本地时间,iso格式使用 UTC - API 交互:与后端 API 交互时,建议使用
iso或timestamp格式 - 显示用途:用于显示时,可以使用
datetime格式
ts
// 应用初始化时设置
import { initORM, setTimeFormat } from '@ibestservices/ibest-orm';
// 设置时间格式
setTimeFormat('datetime');
// 初始化 ORM
initORM({ adapter, logLevel: 'debug' });