GraphQL Date Utilities
Author:
Kirill Gaiduk
Changed on:
24 June 2025
Overview
The `GqlDateUtils`
class in the `util-core`
bundle provides a simple and effective set of functions for handling the specific date format required by the Fluent Commerce GraphQL API. The platform uses the ISO 8601 format (`yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`
), and this utility ensures you can easily parse and format dates to be compatible.
Key points
- GraphQL Compatibility: This utility ensures that dates are always in the precise ISO 8601 string format required by the Fluent Commerce GraphQL API (
`yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`
). - Parsing (
`parseGqlDate`
): Safely parses a string from an event or external system into a standard Java`Date`
object, preventing common parsing errors. - Formatting (
`toGqlDate`
): Converts a Java`Date`
object into the specific string format required when passing dates as variables in GraphQL queries or mutations. - Centralized Logic: Centralizes date handling to avoid bugs and ensure consistency across your entire implementation.
Key Concepts
GraphQL APIs require a precise string format for `DateTime`
fields. This utility centralizes the logic for converting to and from this format, preventing common errors related to date parsing and formatting.
The standard format is: `yyyy-MM-dd'T'HH:mm:ss.SSS'Z'`
- Example:
`2023-10-27T10:30:00.123Z`
Core Methods
`parseGqlDate`
This method parses an object into a standard Java `Date`
. It is designed to be flexible and can handle two types of input:
- A
`java.util.Date`
object (which it will simply pass through). - A
`String`
that is in the correct GraphQL date format.
This is particularly useful when receiving dates from external systems or in event attributes, which may be in string format.
1import com.fluentcommerce.util.core.GqlDateUtils;
2import java.util.Date;
3
4// ...
5
6// An incoming date string from an event attribute or external system
7String dateString = "2023-11-21T15:45:10.000Z";
8
9// Use the utility to parse it into a Date object
10try {
11 Date parsedDate = GqlDateUtils.parseGqlDate(dateString);
12 // Now you can work with the Date object
13} catch (IllegalArgumentException e) {
14 LogUtils.logOnce(
15 context,
16 MyClass.class,
17 "Error parsing date: '%s'",
18 e.getMessage()
19 );
20}
21
22// It also safely handles objects that are already a Date
23Date alreadyADate = new Date();
24Date result = GqlDateUtils.parseGqlDate(alreadyADate); // This works perfectly
`toGqlDate`
To parse a `Date`
object into a `String`
with the format `"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"`
, use the `GqlDateUtils.toGqlDate`
method:
1String currentDate = GqlDateUtils.toGqlDate(new Date());
`getFormat`
To retrieve the date format used by GraphQL, which is `"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"`
, use the `GqlDateUtils.getFormat`
method:
1assertEquals("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", GqlDateUtils.getFormat().toPattern())