Transformations: Support time format when converting time to strings (#63826)

This commit is contained in:
Ryan McKinley
2023-03-01 20:00:53 -08:00
committed by GitHub
parent bc1c54ca17
commit a4fc8b9fca
4 changed files with 77 additions and 13 deletions

View File

@@ -338,6 +338,31 @@ describe('field convert types transformer', () => {
},
]);
});
it('will convert time fields to strings', () => {
const options = {
conversions: [{ targetField: 'time', destinationType: FieldType.string, dateFormat: 'YYYY-MM' }],
};
const stringified = convertFieldTypes(options, [
toDataFrame({
fields: [
{
name: 'time',
type: FieldType.time,
values: [1626674400000, 1627020000000, 1627192800000, 1627797600000, 1627884000000],
},
],
}),
])[0].fields[0];
expect(stringified.values.toArray()).toEqual([
'2021-07',
'2021-07',
'2021-07', // can group by month
'2021-08',
'2021-08',
]);
});
});
describe('ensureTimeField', () => {

View File

@@ -98,7 +98,7 @@ export function convertFieldType(field: Field, opts: ConvertFieldTypeOptions): F
case FieldType.number:
return fieldToNumberField(field);
case FieldType.string:
return fieldToStringField(field);
return fieldToStringField(field, opts.dateFormat);
case FieldType.boolean:
return fieldToBooleanField(field);
case FieldType.other:
@@ -179,17 +179,26 @@ function fieldToBooleanField(field: Field): Field {
};
}
function fieldToStringField(field: Field): Field {
const stringValues = field.values.toArray().slice();
function fieldToStringField(field: Field, dateFormat?: string): Field {
let values = field.values.toArray();
for (let s = 0; s < stringValues.length; s++) {
stringValues[s] = `${stringValues[s]}`;
switch (field.type) {
case FieldType.time:
values = values.map((v) => dateTimeParse(v).format(dateFormat));
break;
case FieldType.other:
values = values.map((v) => JSON.stringify(v));
break;
default:
values = values.map((v) => `${v}`);
}
return {
...field,
type: FieldType.string,
values: new ArrayVector(stringValues),
values: new ArrayVector(values),
};
}