Thoughts

Multiple date formats in one Gatsby GraphQL query

Using some special magic, Gatsby can transform date fields in GraphQL queries into different formats. But what if you would like more than one format, and don't want to import an entire library?

Here is the example the Gatsby docs use for formatString:

1
{
2
allMarkdownRemark(filter: { frontmatter: { date: { ne: null } } }) {
3
edges {
4
node {
5
frontmatter {
6
title
7
date(formatString: "dddd DD MMMM YYYY")
8
}
9
}
10
}
11
}
12
}

My problem was that I wanted a nicely formatted string, but also needed a valid datetime value for a <time> element. Turns out this is really easy in GraphQL queries, but does not turn up in searches (that I could find).

The solution is that you can use field aliases to repeat a field in the same query. This really applies to any field, but becomes especially useful for field transforms.

Here's the same query, but with two different date formats:

1
{
2
allMarkdownRemark(filter: { frontmatter: { date: { ne: null } } }) {
3
edges {
4
node {
5
frontmatter {
6
title
7
relativeDate: date(fromNow: true)
8
isoDate: date(formatString: "YYYY-MM-DDTHH:mm:ssZ")
9
}
10
}
11
}
12
}
13
}

This will result in an object with frontmatter.relativeDate and frontmatter.isoDate:

1
{
2
"data": {
3
"allMarkdownRemark": {
4
"edges": [
5
{
6
"node": {
7
"frontmatter": {
8
"title": "Break with a Banshee",
9
"relativeDate": "28 years ago",
10
"isoDate": "1992-01-01T00:00:00+00:00"
11
}
12
}
13
}
14
]
15
}
16
}
17
}

I'm sure this is obvious to GraphQL pros, but it took me a while to figure this one out, so I wanted to share. Yay for learning!