Skip to content

时间格式

IBest-ORM 支持配置时间戳字段的格式,可以根据需求选择不同的时间格式。

支持的格式

格式示例说明
datetime2024-01-01 12:00:00默认格式,日期时间
date2024-01-01仅日期
time12:00:00仅时间
timestamp1704067200000Unix 时间戳(毫秒)
iso2024-01-01T12:00:00.000ZISO 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

最佳实践

  1. 统一格式:在应用初始化时设置统一的时间格式
  2. 考虑时区datetime 格式使用本地时间,iso 格式使用 UTC
  3. API 交互:与后端 API 交互时,建议使用 isotimestamp 格式
  4. 显示用途:用于显示时,可以使用 datetime 格式
ts
// 应用初始化时设置
import { initORM, setTimeFormat } from '@ibestservices/ibest-orm';

// 设置时间格式
setTimeFormat('datetime');

// 初始化 ORM
initORM({ adapter, logLevel: 'debug' });