Search code examples
angularangular-directive

concatenate string at the end of DateTime


I am using kendoUI for angular I have a common grid with filter functionality. I want to manipulate DateTime record and add "O'clock" at the end of every datetime string. Currently for one datetime filed (as an example) I get the value as "Sun Oct 01 2023 00:00:00 GMT+0200 (Central European Summer Time)" and I wanted to show it like this "03.10.2023 00:00 O'clock"

here is my code

protected mapToDisplayData(): K[] {
    if (!this.data) { return []; }

    return this.data.map((d: K) => {
        const keys = Object.keys(d) as Array<keyof K>;
        const filterable: any = {};
        for (const key of keys) {
            const propValue = d[key];
            filterable[key] = propValue;

            const column = this.gridColumnSettings?.filter(s => s.field === key)[0];
            if (!column) {
                continue;
            }

            if (Array.isArray(propValue)) {
                filterable[key] = propValue.join('');
                continue;
            }
            debugger
            const propValueString = ObjectExtensions.stringify(propValue);

            switch (column.type) {
                case 'status':
                    filterable[key] = this.columnTemplateService.getStatusDisplayValue(propValueString as Status, this.statusDisplayValues);
                    break;
                case 'guid':
                    filterable[key] = this.columnTemplateService.getSlicedGuid(propValueString);
                    break;
                case 'boolean':
                    filterable[key] = this.columnTemplateService.getBooleanDisplayValue(key, propValue as any, this.booleanDisplayValues);
                    break;
                case 'dateTime':
                    filterable[key] =propValue // here I want to append O'clock;
            }
        }
        return filterable;
    });
}

Solution

  • You can define a function as:

    const toCustomFormat = (dateTimeValue) => new Date(dateTimeValue).toLocaleString('de-DE', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        hour12: false
    }).split(', ').join(' ');
    

    Then you can decide if the value returned is equal to 00:00, in which case you can add the ' O'Clock'.

    case 'dateTime':
        const formattedDateTime = toCustomFormat(propValue);
        const isOclock = formatedDateTime.split(' ')[1] === '00:00';
        
        filterable[key] = formattedDateTime + isOclock ? ' O'Clock': '';
    break;
    

    Or you can do the formatting directly inside the case 'dateTime', as:

    propValue.toLocaleString(......