You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Prisma返回巴西时区(UTC-3)的DateTime数据?

解决Prisma全局转换日期到巴西时区的方案

下面提供几个无需为每个实体编写映射器的可行方案,针对你遇到的createdAt/updatedAt时区转换问题:

方案1:使用Prisma客户端扩展(推荐,灵活可控)

利用Prisma的客户端扩展功能,全局拦截所有模型的日期字段,自动转换为巴西时区(America/Sao_Paulo,自动适配夏令时)的格式。

创建扩展后的Prisma实例:

import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient().$extends({
  result: {
    $allModels: {
      createdAt: {
        needs: { createdAt: true },
        compute(model) {
          // 返回格式化后的字符串(可按需调整格式)
          return new Date(model.createdAt).toLocaleString('pt-BR', {
            timeZone: 'America/Sao_Paulo',
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
          });
          // 如果需要返回Date对象而非字符串,可替换为对应逻辑
          // 注意:避免硬编码减3小时,夏令时会导致时间偏差
        }
      },
      updatedAt: {
        needs: { updatedAt: true },
        compute(model) {
          return new Date(model.updatedAt).toLocaleString('pt-BR', {
            timeZone: 'America/Sao_Paulo',
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit'
          });
        }
      }
    }
  }
});

export default prisma;

之后项目中所有查询都使用这个扩展后的实例,所有模型的createdAt/updatedAt会自动转换为巴西时区格式。

方案2:修改数据库连接字符串(最简单,全局生效)

在你的DATABASE_URL中添加时区参数,让PostgreSQL自动将带时区的时间(timestamptz)转换为巴西时区后返回给Prisma:

postgresql://<用户名>:<密码>@<主机>:<端口>/<数据库名>?schema=public&timezone=America/Sao_Paulo

这个方案无需修改代码,所有通过Prisma获取的timestamptz类型字段都会直接返回巴西时区的时间,适合需要全局统一时区的场景。

方案3:全局修改JSON序列化(谨慎使用,有副作用)

如果你的项目基于Node.js(比如Express),可以全局修改JSON序列化规则,自动转换所有Date类型字段到巴西时区:

// Express示例
app.set('json replacer', function(key, value) {
  if (this[key] instanceof Date) {
    return new Date(value).toLocaleString('pt-BR', {
      timeZone: 'America/Sao_Paulo'
    });
  }
  return value;
});

注意:这个方案会影响所有Date类型的序列化,若项目中其他地方需要默认的ISO格式日期,不建议使用。

内容的提问来源于stack exchange,提问作者JoaoVitorLima

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 01:23:15