skip to Main Content

I have got a project where I need to ingest an API feed here http://am-twitter-scrape.herokuapp.com/users/Twitter?pages_limit=3&wait=0

example date string: 2:21 PM - 19 Jul 2019

I need cut off the time and reformat the date like “Month Day, Year” (e.g. Jan 5, 2019).

I have tried to run the datePipe over the string variable like so:

<ng-container matColumnDef="date">
  <th mat-header-cell *matHeaderCellDef> Date </th>
  <!--<td mat-cell *matCellDef="let hashtags"> {{hashtags.date | date: 'longDate'}} </td>-->
  <td mat-cell *matCellDef="let hashtags"> {{hashtags.date}} </td>
</ng-container>

But it just turns up an error saying

InvalidPipeArgument: ‘Unable to convert “2:21 PM – 19 Jul 2019” into a date’ for pipe ‘DatePipe’

Which seems like the date is in a format incompatible with the included Angular toolkit to change the format.

What could be my possible options? Can I use Regex in Angular?

3

Answers


  1. let date = '2:21 PM - 19 Jul 2019';
    let splitDate = date.split('-')[1];
    

    Then you need to use splitDate in your pipe to format it, if it didn’t work then wrap it with new Date(splitDate)

    Login or Signup to reply.
  2. Yes, you can use regex in Angular. However, an easier solution could be using string operations.

    In your template, you can use:

    <td mat-cell *matCellDef="let hashtags"> {{convertDate(hashtags.date)}} </td>
    </ng-container>
    

    And then create the convertDate function in your component:

    convertDate(rawDate: string): string {
      const dateOnly = rawDate.split('-')[1].trim();
      const [day, month, year] = dateOnly.split(' ');
      return `${month} ${day}, ${year}`;
    }
    
    Login or Signup to reply.
  3. You can split the data and parse it using the Date object or momentJs. Once the date is parsed you can change it into any format. For example in your component,

    let date = '2:21 PM - 19 Jul 2019';
    let splitDate = date.split('-')[1];
    hashtags.date = new Date(splitDate);
    

    In your html, you can use,

    <td mat-cell *matCellDef="let hashtags"> {{hashtags.date | date: 'MMMM d, y'}} </td>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search