Unable to retrieve the seconds value from a Timestamp object in Firestore

Currently, I am in the process of developing a Todo application in Angular that utilizes Firestore as the backend. Despite being quite new to Firebase, I am encountering issues when it comes to storing and retrieving dates.

Upon retrieving dates from Firebase and logging them using console.log, I observe an output similar to this: date: _Timestamp { seconds: 1736290800, nanoseconds: 0 }

To convert this into a human-readable format, I recognize the need to access the seconds component and perform a conversion. My attempts at utilizing date.seconds and date.getSeconds() have resulted in errors. The .seconds operation triggers the following error message:

[ERROR] TS2339: Property 'seconds' does not exist on type 'Date'. [plugin angular-compiler]

src/app/pages/todolist/todolist.component.ts:79:47:
  79 │         console.log("date: ",todo.deadlineDate.seconds);

Furthermore, date.getSeconds() is not recognized as a valid function.

The form responsible for fetching the data:

<mat-form-field>
<mat-label>Datum</mat-label>
<input matInput [matDatepicker]="picker" formControlName="date"/>
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>

A glimpse at my interface:

export interface Todo {
    id?: string | null;
    title?: string | null;
    description?: string | null;
    category?: string | null;
    done?: boolean | null;
    dateCreated: Date;
    deadlineDate: Date | null;
}

The function employed for retrieval:

  getAllTodoItems(): Observable<any> {
    return this.firestore.collection('/todo-item').snapshotChanges();
  }

Followed by the method calling the aforementioned function:

    async getTodoItems(): Promise<void>{
      try {
         this.firebaseService.getAllTodoItems().subscribe((data) => {
         this.todoList = data.map((e: any) => {
           const item = e.payload.doc.data();
           return { id: e.payload.doc.id, ...item };
         })
         this.timeStampToDate();
        });
      } catch (error) {
        console.error('Error fetching todo items:', error);
      }
  }

For posting purposes, here's my post function:

  createTodoItem(todo: Todo): Promise<void> {
    todo.id = this.firestore.createId();
    return this.firestore.doc(`/todo-item/${todo.id}`).set(todo);
  }

An issue arises where the date retrieved from Firebase fails to be recognized as a Timestamp object. Attempts to transform the variable into a Timestamp object using Timestamp.fromDate() proved unsuccessful.

Operating within Angular 18 with AngularFirestore, the dates are sourced from user input through MatDatePickerModule and MatNativeDateModule while being stored as Dates within the sent object in Firebase.

If anyone possesses a solution to this problem, I would greatly appreciate your assistance.

Answer №1

If the data you are receiving is in the form of a Firestore.Timestamp object, you will need to convert it into a Date type for further processing. Here is an example of how you can achieve this:

const deadlineDate = todo.deadlineDate; // Assuming this comes from Firestore Timestamp
if (deadlineDate && typeof deadlineDate.toDate === 'function') {
    const humanReadableDate = deadlineDate.toDate(); // Convert Timestamp to Date
    console.log("Converted Date:", humanReadableDate);
} else {
    console.log("The deadline date provided is not a valid Firestore Timestamp.");
}

Once you have converted the Timestamp to a Date, you can utilize Angular's date pipe to display it in your template.

For more details, refer to: https://firebase.google.com/docs/reference/js/firestore_.timestamp.md#timestamptodate

Answer №2

When selecting dateCreated and deadlineDate, you've decided to define them as JavaScript Date objects:

    dateCreated: Date;
    deadlineDate: Date | null;

This means that TypeScript will only recognize them as Dates, not as Firestore Timestamp (even if they are Timestamps at runtime). If the data in your document contains Firestore Timestamp objects, then make sure to type the fields correctly.

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

What advantages does the static modifier offer when used with functions in TypeScript?

My journey with TypeScript has just begun, and while working in WebStorm, the IDE suggested using a static modifier... export default class MyClass { public bar(): any { // perform actions with instance values } private foo(a: any, b: ...

Could an OpaqueToken be assigned using an observable?

I am attempting to establish an opaque token in the providers using an observable. The purpose behind this is that I am retrieving the value through the Http provider (from an external JSON file). This is my current approach: { provide: SOME_ ...

The 'createGame$' property is not found on the 'GameService' object

A new GameService has been crafted with the implementation of the ServiceInterface: export interface ServiceInterface { emitter$; actions: any[]; [action: string]: any; } export class GameService implements ServiceInterface { constructor() { ...

Creating a TypeScript interface that inherits properties from another interface is a powerful way to define

My question pertains to a programming interface I have created called PersonInterface. Within this interface, I have included a property called 'address' which has a type of AddressInterface - another interface that I have defined. I am wondering ...

Steps for importing the config ts file into another ts file in Ionic 2

When trying to import the app.config.ts file in another ts file such as /pages/home/home.ts, I have included the following code in app.config: import { OpaqueToken } from "@angular/core"; export let APP_CONFIG = new OpaqueToken("app.config"); e ...

The 'async' keyword is not permitted in this context within a TypeScript React application

An issue has arisen with the aync, indicating that the async modifier is not permitted in this context: private async getValue= (acc: Access): void => { await this.service.getForm(''); } It appears that there might be an ...

Glitch in Android Radio Button Functionality

Database Structure: https://i.sstatic.net/uDUxc.png Working on a project that involves radio buttons, I am now trying to update data in my FireStore Cloud Database. However, I am encountering a bug that is preventing me from progressing through the IF STA ...

Display the data in ngx-charts heat map

I have been utilizing ngx charts to display data in a Heat Map. The implementation is smooth without encountering any issues. View Working Example | Heat Map However, I am interested in displaying the values of each grid rather than just on mouse hover. ...

Ways to retrieve a list of identifiers from arrays at both initial and subsequent levels

I'm currently dealing with a JSON/JavaScript structure that looks like this: { "comments": [ { "id": 1, "content": "lorem ipsum", "answers": [] }, { "id" ...

Breaking down strings using delimiters in JavaScript

Looking for a solution to parse a string with markers: 'This is {startMarker} the string {endMarker} for {startMarker} example. {endMarker}' I want to transform it into an array that looks like this: [ {marker: false, value: 'This is&ap ...

Transform the React useState hooks to accept props and modify the values of these props

I am currently developing a change password feature with validations. Initially, we utilized state hook functions for validating the input (such as one uppercase character, one lowercase, numbers, etc.) and everything was functioning properly. Now, I am t ...

The dynamic key for an object is not being inferred by Typescript

In my Redux action, I have a simple setup: export interface UpdateUserSettingsPayloadType { videoInput?: MediaDeviceInfo; audioInput?: MediaDeviceInfo; audioOutput?: MediaDeviceInfo; } export const updateUserSettings = ( payload: UpdateUserSetting ...

The chosen sidebar item fails to show the respective component

Is there a way to show a component when the user clicks on the sideNav? Currently, I have managed to display the SideBarNavigation using ng-simple-sidebar. However, when I click on a sidebar item, the component opens as a new page instead of being display ...

Error [ERR_MODULE_NOT_FOUND]: Unable to locate the specified module (TypeScript/TypeOrm)

I'm encountering an issue where the content of my database is not being printed when using an entity with TypeScript/TypeOrm. Here's the code I have: Main file : import { createConnection, getManager ,getConnectionOptions } from 'typeorm&a ...

The library "vue-property-decorator" (v10.X) is causing issues with resolving in Webpack despite being successfully installed

Encountered an error message Module not found: Error: Can't resolve './decorators/Emit' while attempting to import functionality from the library vue-property-decorator. The package is installed and accessible, ruling out a simple installati ...

What steps can be taken to troubleshoot the "error is not assignable to parameter of type" issue in

Do you have any suggestions on how to specify to TypeScript that I am passing the same required argument? Currently, I am encountering an error stating (is not assignable to parameter of type '{ [key: string]: ""; } ). If you could provide g ...

What is the best way to display single data instance from API using Angular?

My API data is structured in a way that includes various questions and their corresponding options. I am looking to display one question and its alternatives at a time, with the ability to move to the next question upon clicking a "Next" button. Since the ...

Error in Typescript: The property 'a' is not defined in the type 'A'

Here is an example of the different types I am working with: type Place = { address: string } type Location = { latLng: string } type User = { name: string } & (Place | Location) When attempting to parse the data using this structure, I enco ...

Firebase initialization is unsuccessful due to an error stating that a source for the codebase must be specified

Encountering an issue with Firebase init functions: Error: codebase source must be specified After deleting the functions directory in order to switch back from typescript to javascript, I anticipated being able to delete and use firebase init for rebuil ...

Setting column width in Angular Material TableIn this article, we will discuss how to define the

<mat-tab class="StatusTab" label="Status"> <mat-table class="table mat-elevation-z10" [dataSource]="statusDetails"> <ng-container matColumnDef="id"> <mat-header-cell *matHea ...