Skip to content

Commit

Permalink
fix(formatter): add possibility to parse a date formatter as a UTC date
Browse files Browse the repository at this point in the history
- e.g. when '2099-12-31T00:00:00.000Z' in my TZ (EST) the DateIso Formatter will transform this in 2099-12-30 instead of 2099-12-31 because it assumes that the TZ must be included
  • Loading branch information
ghiscoding-SE committed Jun 25, 2020
1 parent 032886b commit e72bcad
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 2 deletions.
12 changes: 12 additions & 0 deletions packages/common/src/formatters/__tests__/dateIsoFormatter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,16 @@ describe('the Date ISO Formatter', () => {
const result = Formatters.dateIso(0, 0, value, {} as Column, {});
expect(result).toBe('2019-05-01');
});

it('should return a formatted date value without time date provided has TZ but we specifically mention to parse as UTC ', () => {
const value = new Date(Date.UTC(2099, 11, 31, 0, 0, 0, 0));

const result1 = Formatters.dateIso(0, 0, value, { params: { parseDateAsUtc: true } } as Column, {});
const result2 = Formatters.dateIso(0, 0, value, { params: { parseDateAsUtc: false } } as Column, {});
const result3 = Formatters.dateIso(0, 0, value, {} as Column, {});

expect(result1).toBe('2099-12-31');
expect(result2).toBe('2099-12-30');
expect(result3).toBe('2099-12-30');
});
});
8 changes: 6 additions & 2 deletions packages/common/src/formatters/formatterUtilities.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,14 @@ export function getAssociatedDateFormatter(fieldType: FieldType, defaultSeparato

return (row: number, cell: number, value: any, columnDef: Column, dataContext: any, grid: SlickGrid) => {
const gridOptions = ((grid && typeof grid.getOptions === 'function') ? grid.getOptions() : {}) as GridOption;
const customSeparator = gridOptions && gridOptions.formatterOptions && gridOptions.formatterOptions.dateSeparator || defaultSeparator;
const customSeparator = gridOptions?.formatterOptions?.dateSeparator ?? defaultSeparator;
const isParsingAsUtc = columnDef?.params?.parseDateAsUtc ?? false;

const isDateValid = moment(value, defaultDateFormat, false).isValid();
let outputDate = (value && isDateValid) ? moment(value).format(defaultDateFormat) : value;
let outputDate = value;
if (value && isDateValid) {
outputDate = isParsingAsUtc ? moment.utc(value).format(defaultDateFormat) : moment(value).format(defaultDateFormat);
}

// user can customize the separator through the "formatterOptions"
// if that is the case we need to replace the default "/" to the new separator
Expand Down
Binary file not shown.

0 comments on commit e72bcad

Please sign in to comment.