diff --git a/src/scalars/iso-date/DateTime.ts b/src/scalars/iso-date/DateTime.ts index 2779df420..98fdddbea 100644 --- a/src/scalars/iso-date/DateTime.ts +++ b/src/scalars/iso-date/DateTime.ts @@ -33,7 +33,16 @@ export const GraphQLDateTimeConfig: GraphQLScalarTypeConfig = /*#__P throw createGraphQLError(`DateTime cannot represent an invalid date-time-string ${value}.`); } else if (typeof value === 'number') { try { - return new Date(value); + // This should support 13 and 12-digit timestamps + if ( + (value <= 9999999999999 && value.toString().length === 13) || + (value <= 999999999999 && value.toString().length === 12) + ) { + return new Date(value); + } else { + // Convert to milliseconds + return new Date(value * 1000); + } } catch (e) { throw createGraphQLError('DateTime cannot represent an invalid Unix timestamp ' + value); } diff --git a/tests/iso-date/DateTime.integration.test.ts b/tests/iso-date/DateTime.integration.test.ts index 6e73208d0..a365c0058 100644 --- a/tests/iso-date/DateTime.integration.test.ts +++ b/tests/iso-date/DateTime.integration.test.ts @@ -26,6 +26,10 @@ const schema = new GraphQLSchema({ type: GraphQLDateTime, resolve: () => '2016-02-01T00:00:00-11:00', }, + validUnixTimestamp: { + type: GraphQLDateTime, + resolve: () => 854325678, + }, validUnixTimestamp: { type: GraphQLDateTime, resolve: () => 854325678000, diff --git a/tests/iso-date/DateTime.test.ts b/tests/iso-date/DateTime.test.ts index 8157e56c9..dbe6938ce 100644 --- a/tests/iso-date/DateTime.test.ts +++ b/tests/iso-date/DateTime.test.ts @@ -87,11 +87,16 @@ describe('GraphQLDateTime', () => { // Serializes Unix timestamp [ [854325678000, '1997-01-27T00:41:18.000Z'], - [876535000, '1970-01-11T03:28:55.000Z'], - // The maximum representable unix timestamp + [854325678, '1997-01-27T00:41:18.000Z'], + [866478, '1970-01-11T00:41:18.000Z'], + [1713305032000, '2024-04-16T22:03:52.000Z'], + [1713305032, '2024-04-16T22:03:52.000Z'], + // The maximum representable unix timestamp in milliseconds [2147483647000, '2038-01-19T03:14:07.000Z'], + // The maximum representable unix timestamp in seconds + [2147483647, '2038-01-19T03:14:07.000Z'], // The minimum representable unit timestamp - [-2147483648000, '1901-12-13T20:45:52.000Z'], + [-2147483648, '1901-12-13T20:45:52.000Z'], ].forEach(([value, expected]) => { it(`serializes unix timestamp ${stringify(value)} into date-string ${expected}`, () => { expect(GraphQLDateTime.serialize(value).toJSON()).toEqual(expected);