All files / libs/amalia-lang/formula/evaluate/shared/src/functions/dates/to-date index.ts

100% Statements 53/53
100% Branches 2/2
100% Functions 1/1
100% Lines 53/53

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 541x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
import { AmaliaFunctionCategory, AmaliaFunctionKeys, type AmaliaFormula } from '@amalia/amalia-lang/formula/types';
import { TokenType } from '@amalia/amalia-lang/tokens/types';
import { FormatsEnum } from '@amalia/data-capture/fields/types';
import { dayjs } from '@amalia/ext/dayjs';
 
import { AmaliaFunctionDefault } from '../../AmaliaFunction';
 
export const datesToDate = new AmaliaFunctionDefault<[string, string?], number>({
  name: AmaliaFunctionKeys.toDate,
  category: AmaliaFunctionCategory.DATES,
  nbParamsRequired: 1,
  description: 'Convert any date format to a timestamp',
 
  // A format can be specified if the date is not formatted like `YYYY-MM-DD`. Format allows using a single digit for months and days.
  // The date will be formatted by dayjs (see documentation here https://momentjs.com/docs/#/parsing/string-format/ or examples below).
  exec: (dateString, format) => dayjs(dateString, format || 'YYYY-M-D').unix(),
 
  params: [
    {
      name: 'dateString',
      description: 'Date in any format: variables, properties, fields, keywords or a specific date in defined format',
      validTokenTypes: [TokenType.VARIABLE, TokenType.PROPERTY, TokenType.FIELD, TokenType.KEYWORD],
      validFormats: [FormatsEnum.date, FormatsEnum['date-time']],
    },
    {
      name: 'format',
      description: 'Format of the dateString that is by default YYYY-MM-DD',
      defaultValue: 'YYYY-MM-DD',
    },
  ],
 
  examples: [
    {
      desc: 'Returns 1685577600.',
      formula: 'toDate("2023-06-01")' as AmaliaFormula,
      result: 1_685_577_600,
    },
    {
      desc: 'Returns 1685577600.',
      formula: 'toDate("2023/06/01", "YYYY/MM/DD")' as AmaliaFormula,
      result: 1_685_577_600,
    },
    {
      desc: 'Returns 1685577600 for June 1st 2023.',
      formula: 'toDate("Jun 23", "MMM YY")' as AmaliaFormula,
      result: 1_685_577_600,
    },
    {
      desc: 'Returns Close Date in timestamp converted from a MMM YY format.',
      formula: 'toDate(opportunity.closeDate, "MMM YY")',
    },
  ],
});