GraphQL - DateTime 未以本地时区值显示时间
Posted
技术标签:
【中文标题】GraphQL - DateTime 未以本地时区值显示时间【英文标题】:GraphQL - DateTime not showing time in local timezone value 【发布时间】:2020-01-04 22:11:58 【问题描述】:我正在使用 GrapQL、Node 和 PostgreSQL 开发一个待办事项列表应用程序。
作为我的实体,我有一张卡片,其中包含 DateTime 的这些字段: created_at 和 updated_at。
我设法创建一个标量 Date 来管理 DateTime 格式,但时间采用以下格式:
"created_at": "2019-08-24T23:11:02.376Z",
"updated_at": "2019-09-01T15:04:12.627Z"
我想要显示我所在时区的实际时间的格式。上面的时间是Z
,比我的时间晚了2小时。
我的标量日期如下:
import GraphQLScalarType, GraphQLError from 'graphql';
import Kind from 'graphql/language';
import isISO8601 from 'validator';
export default new GraphQLScalarType(
name: 'Date',
description: 'Date type',
parseValue(value): Date
if (isISO8601(value))
// value comes from the client
return new Date(value); // sent to resolvers
throw new Error('DateTime cannot represent an invalid ISO-8601 Date string');
,
serialize(value): Promise<string>
if (isISO8601(value))
// value comes from resolvers
return value.toISOString(); // sent to the client
throw new Error('DateTime cannot represent an invalid ISO-8601 Date string');
,
parseLiteral(ast): Date
// ast comes from parsing the query
// this is where you can validate and transform
if (ast.kind !== Kind.STRING)
throw new GraphQLError(`Query error: Can only parse dates strings, got a: $ast.kind`, [ast]);
if (isNaN(Date.parse(ast.value)))
throw new GraphQLError(`Query error: not a valid date`, [ast]);
if (isISO8601(ast.value)) return new Date(ast.value);
throw new Error('DateTime cannot represent an invalid ISO-8601 Date string');
,
);
我的卡片实体:
import Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn from 'typeorm';
@Entity('cards')
export class Card
@PrimaryGeneratedColumn('uuid')
id: string;
@CreateDateColumn()
created_at: Date;
@UpdateDateColumn()
updated_at: Date;
@Column('text')
title: string;
@Column('text',
nullable: true,
)
description: string;
@Column('boolean',
default: 'false',
)
done: boolean;
卡片类型:
export const Card = `
scalar Date
type Card
id : String
title : String
description : String
done : Boolean
created_at : Date
updated_at : Date
`;
【问题讨论】:
【参考方案1】:在客户端,您可以使用moment 来格式化您的返回日期,
你也可以在后端使用moment框架,
但您需要设置当地时区:
moment(yourDate).local("your-local");
示例:
moment("2019-08-24T23:11:02.376Z").local("ar-IQ");
【讨论】:
在构建客户端时可以使用该解决方案。目前我正在构建一个 API,我需要知道我是否可以在后端进行更改,或者了解为什么最好不进行更改,并在未来仅将其保留在客户端。 我已经更新了我的答案,我认为最好在客户端这样做,希望对你有所帮助 你能告诉我一个使用我上面的代码的例子吗?如何利用这一刻来做到这一点? 非常抱歉我不熟悉 GraphQL api,但我建议在客户端转换日期,因为您不知道客户端从哪个时区请求 api【参考方案2】:我可以举个例子如何转换SQL中的时间戳:据我了解Z
与UTC
相同。
因此,为了获取“您的”时区中的日期和时间,您可以使用以下语法 select
它:
# Example: America/Campo_Grande
select created_at at time zone 'utc' at time zone 'America/Campo_Grande' from cards;
https://www.postgresql.org/docs/10/functions-datetime.html#FUNCTIONS-DATETIME-ZONECONVERT
我不知道如何在这个特定的 GraphQL 环境中做到这一点。
【讨论】:
以上是关于GraphQL - DateTime 未以本地时区值显示时间的主要内容,如果未能解决你的问题,请参考以下文章
通过忽略时区将 JSON DateTime 对象解析为 JQuery 中的本地时间