PostgreSQL 输出与 Javascript 时间戳格式不同的时间戳格式

PostgreSQL outputs different TimeStamp format than Javascript TimeStamp format

我无法将 SQL 的结果绑定到我在 Javascript /Typescript 中的模型。

在我的模型中,我有 created_at 的 属性,类型为 Date

当我在 Postgres SQL 语句中使用 JSON 函数来避免关系的重复父行时,我将获得不同格式的时间戳。

这是一个简单的例子

SELECT
   a.*,
   (
      SELECT
         ROW_TO_JSON(profile) 
      FROM
         (
            SELECT
               *
            FROM
               profile p 
            WHERE
               p.account_id = a.id 
         )
         profile 
   )
   AS profile 
FROM
   account a 
WHERE
   a.id = 16

这里是 JSON

中的结果
{
   "id":16,
   "email":"test@gmail.com",
   "password":"$password",
   "role_id":0,
   "created_at":"2020-04-01T22:03:44.324Z",
   "profile":{
      "id":8,
      "username":"firmanjml",
      "gender":0,
      "bio":null,
      "avatar":"www.firmanjml.me/test.jpg",
      "account_id":16,
      "created_at":"2020-04-02T06:03:44.32498"
   }
}

我注意到来自帐户 table 的父行在 created_at 的末尾有 Z,而转换为 JSON 的子行 table具有不同的时间戳格式。

有没有办法让所有时间戳都采用 Javascript 格式?

创建模式和插入数据的查询

CREATE TABLE "account"(
    id SERIAL primary key,
    email varchar(50) not null,
    password varchar(50) not null,
    role_id int2 default 0 not null, 
    created_at timestamp default now() not null
);

CREATE TABLE "profile"(
    id SERIAL primary key,
    username varchar(50) not null,
    gender int2 not null,
    bio varchar(50),
    avatar varchar(50),
    account_id integer not null REFERENCES account (id),
    created_at timestamp default now() not null
);

INSERT INTO "account" (email,"password","role_id",created_at) VALUES 
('test@gmail.com','$password',0,'2020-04-02 06:03:44.324');

INSERT INTO "profile" (username,gender,bio,avatar,account_id,created_at) VALUES 
('fimrnajml',0,NULL,'www.firmanjml.me/test.jpg',1,'2020-04-02 06:03:44.324');

使用 TO_CHAR() 函数格式化 SQL 中的时间戳,例如 https://www.postgresqltutorial.com/postgresql-to_char/

'YYYY-MM-DD"T"HH24:MI:SS.US"Z"' 的格式应该可以做到。这假设你所有的时间戳都是 UTC(专业人士这样做的方式:-)

你的 SQL 看起来像:

SELECT
   a.*,
   (
      SELECT
         ROW_TO_JSON(profile) 
      FROM
         (
            SELECT
               username,gender,bio,avatar,account_id,to_char(created_at, 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') created_at
            FROM
               profile p 
            WHERE
               p.account_id = a.id 
         )
         profile 
   )
   AS profile 
FROM
   account a
WHERE
   a.id = 16

试一试here