Angular TypeScript DatePipe throwing a "invalidPipeArgument: 'Cannot convert "03:45:00" into a date'" error

My goal is to display just the hours and minutes of a Date object retrieved from an API on the frontend as 'shortTime' format.

However, when I attempt to do so with the following code:

<h2>{{data.scheduleTime | date:'shortTime'}} - {{data.actualLandingTime | date:'shortTime'}}</h2><br>

I encounter the following error: InvalidPipeArgument: 'Unable to convert "03:45:00" into a date' for pipe 'DatePipe'

I suspect that Angular is having trouble identifying the object as a Date type...

The JSON objects are received through an API call. I have defined a model to specify the types of the objects. Both "scheduleTime" and "actualLandingTime" are dates in the model:

The FlightInfoModel looks like this:

actualLandingTime:           Date;
scheduleTime:                Date;

The data is received in the following format:

actualLandingTime: "2020-04-29T03:17:33.000+02:00"
scheduleTime: "03:45:00"

I only want to display the hours and minutes for both fields..

To take a closer look at the issue, here is how I fetch the API for that page:

data: FlightInfoModel;

  ngOnInit(): void {


    this.flightService.getFligthInfo<any>('129392719696922308').subscribe(response => {this.data = response, console.log(response)},
        error => console.log(error));


  }

Answer №1

The information being received for the scheduleTime does not adhere to a valid date format as it only contains the time. A workaround solution would be to instantiate a new Date object with an arbitrary year, month, day, and the time retrieved from the string.

let scheduleDate = new Date(2020, 4, 4, ...scheduleTime.split(':').map(t => Number(t));

This action will input the hour, minute, and second of the time string into the Date constructor.

You could implement something similar to the code above within a map step (i.e., by utilizing the rxjs map operator on your observable response). Additionally, consider changing the type of scheduleTime to Date | string and converting it whenever it is a string instead of a Date instance.

Below is a comprehensive example of the code:

this.flightService.getFligthInfo<any>('129392719696922308').pipe(
  map(info => {
    if(typeof info.scheduleTime === "string") {
       const splitTime: number[] = (<string>info.scheduleTime)
         .split(':')
         .map(t => Number(t));
       return {
         actualLandingTime: info.actualLandingTime,
         scheduleTime: new Date(2020, 4, 4, ...splitTime)
       }
    }
    return info
  }
)

Remember to include importing map from rxjs/operators

When passing this through the date pipe, it will recognize it as a valid Date.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating and setting a selected option dynamically in Angular 2 for editing purposes

As I attempt to modify a user, I encounter a scenario where the user possesses a non-primitive array of machines. During editing, my goal is to generate new elements with select options and assign the selected value based on the user object: export class ...

Using Protractor: Verifying if an input field is in focus and ready for text input

Is there a way to determine if an input field has focus? I attempted the following approach: in my .po.ts getEditInputField(fieldName: string) { return $(`input[data-e2e=${fieldName}]`) } In my .spec.ts it("should focus the Abschlag input field", ...

The navigation bar is struggling to be positioned on top of the body

I have encountered an issue where I want my navbar to remain on top of all components, but when I open the navigation menu, it pushes all the components of the index page down. My tech stack includes Next.js, Tailwind CSS, and Framer Motion. This problem ...

Definition of Stencil Component Method

I'm encountering an issue while developing a stencil.js web component. The error I'm facing is: (index):28 Uncaught TypeError: comp.hideDataPanel is not a function at HTMLDocument. ((index):28) My goal is to integrate my stencil component i ...

Angular HTML Component Refactor causes compatibility issues with BS4 classes

Currently, I am working on Angular components and I have a specific section that I would like to refactor into a separate component for reusability. Initially, when the HTML block with only Bootstrap 4 classes is placed in the parent component, the user in ...

Challenges in designing an Angular application: tackling the spinner and autocomplete functionality

Looking to connect to a REST API that returns a JSON response for implementation of a self-completion feature. The aim is to display a spinner during the autocompletion process until the data retrieval is complete. Although the autocomplete functionality ...

When I run ng build, an error code ".form-floating>~label" pops up

After running the command "ng build" in my Angular app, I encountered the following output: ✔ Browser application bundle generation complete. ✔ Copying assets complete. ⠋ Generating index html...4 rules skipped due to selector errors: .form-floatin ...

The CosmosClient's read() method will only return an object if both the ID and partition key value are provided

After setting up a CosmosDB instance and inserting a test object into the container products, with the partition key set to /price, I encountered an issue. The item added had the following properties: { "id": "1234", "name": "A DB product", "p ...

The TypeScript type for a versatile onChange handler in a form

Let's skip the function declaration and dive into writing the current types for state, and the state itself. type BookFormState = { hasError: boolean; } BookForm<BookFormState> { ... state = { hasError: false }; Next, inside the class ...

Using angular to pass a list of strings as a query parameter in an http.get request

Within my API, I have a get method that takes an ID in the path and a list of dates as query parameters. However, when my http service tries to retrieve this data, I encounter the following error: public ObterSimulacao<T>(inscricao: string, listaDat ...

Sharing boolean values between Angular components is not working as expected

I'm working on a simple use case but seem to be missing something. In this scenario, I have two components: componentA and componentB. I am trying to pass a boolean value from componentB to componentA using an eventEmitter in order to show/hide a spe ...

Add a pair of unique files to your Mean stack project

Is there a way to upload two different files using multer? I've tried using upload.fields but it didn't work. Any help on how to resolve this would be greatly appreciated. schoolpass.component <div class="col-md-4"> ...

When a service alias is provided in Angular 7, it disrupts the build execution process

After creating a service called MyService and its mocked version - MyServiceMock, I utilized the mock service in my unit tests until the backend is ready, providing and using the results from the mocked service. To avoid future code changes when the backe ...

Troubleshooting Problem with RXJS Subject Wrapper

I'm facing a challenge with my class that contains an RXJS Subject. I want to create a shorthand in the class that allows for easy piping or subscribing without directly accessing the subject. However, I've encountered some issues while trying to ...

Refresh Ionic 2 Platform

I'm currently working on an Ionic 2 app and whenever I make a change to the .ts code, I find myself having to go through a tedious process. This involves removing the platform, adding the Android platform again, and then running the app in Android or ...

Upload button allowing multiple values to be uploaded as a single file

I'm currently facing an issue with my list of values and upload buttons. The file upload functionality is working correctly, but the problem arises when I try to upload a file for any item in the list - it always uploads for the first item only. Here ...

What is the best way to categorize variables?

How can I organize variables together: export let findbyc$: Observable<Object>; export let findbyi$: Observable<Object>; export let findbyo$: Observable<Object>; export let findbyob$: Observable<Object>; I would like to group them ...

Drizzle ORM retrieve unique string that is not a database column

I'm working with a SQL query that looks like this: SELECT * FROM ( SELECT 'car' AS type, model FROM car UNION SELECT 'truck' AS type, model FROM trucks ) vehicles; In Drizzle, I'm trying to replicate the 'car ...

CSS - Text and dropdown misalignment due to spacing issue

I'm looking to decrease the spacing between the text "Allow type of Compartment Option" and the dropdown box. Here is the code snippet being used: .cl-checkbox { padding-left: 20px; padding-bottom: 10px; padding-top: 20px; ...

Can you explain the concept of TestBed in Jasmine?

Recently, I have started using Jasmine with Angular 2 and have encountered an issue while working with the TestBed object in my test cases. The error message reads as follows: Please call "TestBed.compileComponents" before your test. Can anyone advise on ...