Zod 通过预处理解析时间字符串为 Unix 时间戳

Created at: 2025-11-28T00:00:00.000Z

从 RFC3399 转换成 Unix 时间戳

从 PocketBase 获取的时间格式是 RFC3399 格式的字符串,和其他的时间值比较的时候最好转成 js 的 Date 对象或者 unix 时间戳,我个人更喜欢直接使用时间戳

"2022-01-01 10:00:00.123Z" -> Zod Object parse() -> 1764322864

const processDateData = (value: unknown) => {
  if (typeof value === "string" || typeof value === "number") {
    const date = dayjs(value);
    return date.isValid() ? date.unix() : value;
  }
  return value;
};

const baseSchema = z.object({
  id: z.string(),
  created: z.preprocess(processDateData, z.number().int().min(0)),
  updated: z.preprocess(processDateData, z.number().int().min(0)),
});

转回 RFC3399

baseSchema.parse() 输入的 createdupdated 同时支持数字和字符串,字符串由 dayjs 解析。

另外加一条转回 RFC3399 的片段:

dayjs(timestamp).toISOString().split("T").join(" ");