Home > OS >  How to specify DateTime in GraphQL schema?
How to specify DateTime in GraphQL schema?

Time:12-06

I am building my GraphQL schema for my project and one of my models has a DateTime format.

How do I write out date formats on my GraphQL schema?

I tried DateTime or Date but nothing shows up.

This is the model:

public Integer Id;
public String name;
public String description;
public LocalDate birthDate;

This is what's in my GraphQL schema:

type Pet {
    id: ID!
    name: String!
    description: String
    birthDate: DateTime
} 

But it says:

Unknown type DateTime

CodePudding user response:

In GraphQL, the DateTime type is represented by the DateTime scalar type, which can be used to represent date and time values in your schema. To use the DateTime scalar type in your schema, you can specify it as the type for the birthDate field in your Pet type, like this:

type Pet {
  id: ID!
  name: String!
  description: String
  birthDate: DateTime
}

In this example, the birthDate field is declared as a DateTime type, which allows it to represent date and time values. When querying this field, you can use the DateTime scalar type to specify the format for the date and time value that is returned. For example, you could use the dateTime or date format strings to specify the format for the date and time value, like this:

query {
  pet(id: 1) {
    name
    birthDate(formatString: "dateTime")
  }
}

In this example, the formatString argument is used to specify the dateTime format for the birthDate field, which will return the date and time value in the YYYY-MM-DDTHH:mm:ss.sssZ format. You can also use the date format string to return the date value only, in the YYYY-MM-DD format.

It is important to note that the DateTime scalar type is only available in GraphQL versions 1.8 and later. If you are using an earlier version of GraphQL, you may need to use a custom scalar type or a string-based type to represent date and time values in your schema.

  • Related