Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
GraphQLTimestamp.js
import { Kind } from 'graphql/language';
import { GraphQLScalarType } from 'graphql';
function serializeDate(value) {
if (value instanceof Date) {
return value.getTime();
} else if (typeof value === 'number') {
return Math.trunc(value);
} else if (typeof value === 'string') {
return Date.parse(value);
}
return null;
}
function parseDate(value) {
if (value === null) {
return null;
}
try {
return new Date(value);
} catch (err) {
return null;
}
}
function parseDateFromLiteral(ast) {
if (ast.kind === Kind.INT) {
const num = parseInt(ast.value, 10);
return new Date(num);
} else if (ast.kind === Kind.STRING) {
return parseDate(ast.value);
}
return null;
}
const TimestampType = new GraphQLScalarType({
name: 'Timestamp',
description:
'The javascript `Date` as integer. Type represents date and time ' +
'as number of milliseconds from start of UNIX epoch.',
serialize: serializeDate,
parseValue: parseDate,
parseLiteral: parseDateFromLiteral,
});
export default TimestampType;
@anaborgessensedia

This comment has been minimized.

Copy link

commented Sep 19, 2017

Thanks. I was having problems with GraphQLDateTime. Your Script was the solution.

@billel-boudchicha

This comment has been minimized.

Copy link

commented Oct 16, 2017

Thank you very much

@dandv

This comment has been minimized.

Copy link

commented Jul 15, 2018

For those who prefer to import an npm package with documentation and all, there's grapql-iso-date.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.