@prismicio/client
Version:
The official JavaScript + TypeScript client library for Prismic
1 lines • 2.33 kB
Source Map (JSON)
{"version":3,"file":"asDate.cjs","names":[],"sources":["../../src/helpers/asDate.ts"],"sourcesContent":["import type { DateField } from \"../types/value/date\"\nimport type { TimestampField } from \"../types/value/timestamp\"\n\n/**\n * The return type of `asDate()`.\n */\ntype AsDateReturnType<\n\tField extends DateField | TimestampField | null | undefined,\n> = Field extends DateField<\"filled\"> | TimestampField<\"filled\"> ? Date : null\n\n/**\n * Converts a date or timestamp field to a JavaScript Date object.\n *\n * @example\n *\n * ```ts\n * const date = asDate(document.data.release_date)\n * // => Date object or null\n * ```\n *\n * @param dateOrTimestampField - A date or timestamp field from Prismic.\n *\n * @returns A Date object, or `null` if the field is empty.\n *\n * @see Learn about date and timestamp fields: {@link https://prismic.io/docs/fields/date}\n */\nexport const asDate = <\n\tField extends DateField | TimestampField | null | undefined,\n>(\n\tdateOrTimestampField: Field,\n): AsDateReturnType<Field> => {\n\tif (!dateOrTimestampField) {\n\t\treturn null as AsDateReturnType<Field>\n\t}\n\n\t// If field is a timestamp field...\n\tif (dateOrTimestampField.length === 24) {\n\t\t/**\n\t\t * Converts basic ISO 8601 to ECMAScript simplified ISO 8601 format for\n\t\t * browser compatibility issues\n\t\t *\n\t\t * From: YYYY-MM-DDTHH:mm:ssZ To: YYYY-MM-DDTHH:mm:ss.sssZ\n\t\t *\n\t\t * @see MDN documentation: {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date#timestamp_string}\n\t\t * @see ECMAScript 2020 language specification: {@link https://262.ecma-international.org/11.0/#sec-date-time-string-format}\n\t\t * @see Related forum issue: {@link https://community.prismic.io/t/prismics-date-api/2520}\n\t\t * @see Regex101 expression: {@link https://regex101.com/r/jxyETT/1}\n\t\t */\n\t\treturn new Date(\n\t\t\tdateOrTimestampField.replace(/(\\+|-)(\\d{2})(\\d{2})$/, \".000$1$2:$3\"),\n\t\t) as AsDateReturnType<Field>\n\t} else {\n\t\t// ...else field is a date field\n\t\treturn new Date(dateOrTimestampField) as AsDateReturnType<Field>\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA0BA,MAAa,UAGZ,yBAC6B;AAC7B,KAAI,CAAC,qBACJ,QAAO;AAIR,KAAI,qBAAqB,WAAW;;;;;;;;;;;;AAYnC,QAAO,IAAI,KACV,qBAAqB,QAAQ,yBAAyB,cAAc,CACpE;KAGD,QAAO,IAAI,KAAK,qBAAqB"}