0

I want to check whether the data coming from loop in p-table is of string type or date type

I have a key named newValue whose value can be either newValue: "Percentage" or newValue: "2021-03-25T15:55:42.136Z"

If its date I want to show the data as "3/25/21, 9:25 PM" else normal string "Percentage"

 <td style="width: 10%;">
        {{rowData?.histories.newValue ? getDateorStringValue(rowData?.histories.newValue) : 'N/A'}}
      </td>
    getDateorStringValue(...) 

is the function I am using any idea how to achieve this?

Juhi Shaw
  • 37
  • 7

1 Answers1

1

You could write a quick pipe to do the comparison.

date-or-string.pipe.ts

import { Inject, LOCALE_ID, Pipe, PipeTransform } from "@angular/core";
import { DatePipe } from "@angular/common";

export const isDate = (date: string) => {
  return !!Date.parse(date);
};

@Pipe({
  name: "dateOrString"
})
export class DateOrStringPipe extends DatePipe implements PipeTransform {
  constructor(@Inject(LOCALE_ID) locale: string) {
    super(locale);
  }

  transform(
    value: any,
    format?: string,
    timezone?: string,
    locale?: string
  ): any {
    return isDate(value)
      ? super.transform(value, format, timezone, locale)
      : value;
  }
}

Usage

<td style="width: 10%;">
  {{ rowData.histories.newValue | dateOrString:'M/dd/yy, h:mm a'}}
</td>

Note that the condition using Date.parse() might only work when compared against string. There are better ways to compare that you could find here.

Working example: Stackblitz

ruth
  • 29,535
  • 4
  • 30
  • 57
  • constructor(@Inject(LOCALE_ID) locale: string) { super(locale); } what is the use of this? – Juhi Shaw Mar 26 '21 at 11:23
  • 1
    It's the Angular standard `Date` pipe's [constructor parameter](https://github.com/angular/angular/blob/11.2.7/packages/common/src/pipes/date_pipe.ts#L156). Since we are extending the standard `Date` pipe, it must be passed in our child class's constructor. – ruth Mar 26 '21 at 11:26
  • !!Date.parse(date) it returns true if value is 50, which is wrong but return false if value is 25, which is correct why? @michael-d – Juhi Shaw Apr 06 '21 at 11:55