Displaying and verifying the current date with JHipster

It may sound strange, but I'm having trouble figuring out how to compare a date field in an HTML created by JHipster test if it's greater than the current date.

I attempted to display the date fetched from the database as 2020-12-12 and then tried to show the current date. After searching online, I found that it's possible to obtain the current date using: new Date(). However, when I try to display this on the page, I encounter an error:

ERROR Error: Uncaught (in promise): Error: Template parse errors:
Parser Error: Unexpected token 'Date' at column 5 in [ {{new Date()}} ] in...

How do I retrieve the current date for comparison with the one retrieved from the database?

Below is the code from myclass.component.html where I need to validate the date:

<div>
    <jhi-alert-error></jhi-alert-error>
...
    <div class="table-responsive" *ngIf="myclasses?.length > 0">
        <table class="table table-striped" aria-describedby="page-heading">
            <thead>
            <tr jhiSort [(predicate)]="predicate" [(ascending)]="reverse" [callback]="transition.bind(this)">
            <th...
            </tr>
            </thead>
            <tbody>
            <tr *ngFor="let myclasse of myclasses ;trackBy: trackId">
                <td>{{myclass?.id}}</td>
                ...
                <td>
                  {{ new Date() }}
                </td>
 ...

Answer №1

Typically, dealing with dates is more convenient when using the MomentJS library since it comes integrated into JHipster already.

If you want to determine if a date is in the future, you can create a function in your [entity].component.ts file that returns a boolean value as shown below:

import * as moment from 'moment';
import { Moment } from 'moment';
...
  isFutureDate(date: Moment): boolean {
    return moment().isBefore(date);
  }

You can then call this function in your [entity].component.html like this:

<td>
  Date is in the future: {{ isFutureDate(myclass.date) }}
</td>

In case you just need to calculate the difference between a specific date and the current time, you can easily do so. In your ...component.ts:

import * as moment from 'moment';
import { Moment } from 'moment';
...
  getDateDiff(date: Moment): number {
    const diff      = date.diff(moment());
    const duration  = moment.duration(diff);
    return duration.asHours();
  }

And in your ...component.html:

<td>
  Difference in hours: {{ getDateDiff(myclass.date) | number: '2.0-0' }} hours
</td>

The getDateDiff() function will provide the difference in hours between the specified date parameter (myclass.date) and the current date (moment()). The result will be negative if the date is in the past.

MomentJS offers robust functionalities, and you can explore its detailed documentation here. Additionally, you can refer to the following links for more information on the methods used:

  • isBefore(): Determines if one date is before another
  • diff(): Calculates the difference between two dates in milliseconds
  • duration(): Facilitates working with time durations efficiently
  • asHours(): Retrieves the total number of hours in a duration

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

Steps to deactivate a button in an Angular reactive form upon submission

I am working with Angular reactive forms and I need to implement a functionality where the button is disabled and its label changes after it has been clicked or submitted. Any suggestions on how to achieve this? ...

Encountering Error: Unable to create new component as PriorityQueue is not recognized as a constructor

While trying to create a new component using Angular CLI with the command ng g c navbar, I encountered an unusual error message: core_1.PriorityQueue is not a constructor TypeError: core_1.PriorityQueue is not a constructor at new TaskScheduler (/h ...

Modifying audio output in a React element

I am trying to incorporate background music into my React app using TypeScript. However, I am encountering an issue where changing the music in the parent component does not affect the sound playing in the child node. import React from 'react'; ...

Leverage the power of Filesaver.js in conjunction with Angular

I've searched through all the articles I could find about integrating Filesaver JS with Angular, but I'm still struggling to find a solution that works for me. In my system.config.js file, I included the following code in the map section: ' ...

The challenge of validating component compositions

I wanted to streamline the process of creating simple forms by avoiding repetitive components. To achieve this, I designed a few components that group other inputs together. Check out my example project: https://stackblitz.com/edit/angular-material-with-a ...

Require using .toString() method on an object during automatic conversion to a string

I'm interested in automating the process of utilizing an object's toString() method when it is implicitly converted to a string. Let's consider this example class: class Dog { name: string; constructor(name: string) { this.name = na ...

Function that yields promise result

I need help figuring out how to make this recursive function return a promise value. I've attempted various approaches, but they all resulted in the search variable ending up as undefined. public search(message: Message) { let searchResult: strin ...

Error: Unable to locate bundle.js when attempting to refresh the page with a specific ID in the URL

I encountered an issue where I tried redirecting a user to their profile page to display the profile information corresponding to it. Let's say we have http://localhost:8080/user/1 as an example. Upon redirecting the user using the navbar link, the pa ...

Error occurred when attempting to link user services with report controller

Greetings, I am currently working on a Nest Js mini project that consists of two separate modules: reports and users. Each module has its own Service, controller, and repositories. The reports module has a many-to-one relation with the users module. My g ...

Mastering the Art of Handling Postgres Error Messages for Accurate Query Execution

Currently, I am utilizing pg and node.js. The issue arises when a user logs in through the auth0 widget, as I am passing the returned email to check against my database for existing users. If the user does not exist, I am inserting their information into t ...

Typescript iteration: Exploring an iterable through multiple traversals

What is a practical approach to handling multiple traversals over an Iterable in Typescript? Typically, an Iterable can only be traversed once before it exhausts all its elements. For instance, an IterableIterator behaves this way. To traverse a sequence ...

Is it possible to release a typescript package without including the ts files in the

I have a Typescript project that needs to be published. All generated JS files are stored in a directory named build, and declaration files in another directory called declaration. I do not want the .ts files to be included in the published version. Can an ...

primeng: Version 16.2.0 of Angular - Get it now!

Upon setting up angular 16.0.0 locally, I used the following command: npx -p @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b6d5dadfdcc49a8fb2a4beb4beb4">[email protected]</a> ng new Tester --no-stand ...

Using Promise.all like Promise.allSettled

I am looking to streamline the handling of Promise.allSettled in a more generic way. Currently when using allSettled, it returns a list of both fulfilled and rejected results. I find this cumbersome and do not want to handle it everywhere in my code. My g ...

Error: The type property of ngmodule is failing to be read as it returns null in the main

I am currently in the process of updating my app to utilize RC5 by bootstrapping it using a module. Encountering this error: https://i.sstatic.net/hlpKn.png Upon investigating the error further, I discovered the following information: Error: TypeError: ...

"Create a special pipe system to filter an empty array

After creating a custom pipe, I incorporated it into my project: @Pipe({ name: 'orderBy' }) export class OrderByPipe implements PipeTransform { transform(items: any[], orderBy: string): any[] { if (items && items.length > ...

Best practices for Angular: Managing concurrent http requests

Imagine I need to upload 100 images through my Angular frontend, which means making 100 API calls. However, the backend has restrictions in place that only allow a maximum of 5 API requests to be executed simultaneously. As each request is completed, ano ...

The absence of a function implementation right after the declaration within a TypeScript class is a common issue that needs

I received a handwritten array to populate a table for my class, however I am now fetching this array's content from a JSON during the ngOnInit phase and it is not structured in the way I require. Therefore, I am attempting to create a function that ...

Edge Runtime does not permit the use of Dynamic Code Evaluation functions such as 'eval', 'new Function', and 'WebAssembly.compile'

My project involves the implementation of NextUI components. I incorporated the Select component from NextUI, and during development mode, everything functioned flawlessly. However, upon completion of development and attempting to build the project, I enc ...

What is the best way to remove any objects in this array that have empty strings as values?

I have been developing a form using Angular 14. The form consists of a primary section, which includes the user's necessary information, and a secondary section where users can input additional data (an array of residences displayed in a table) befor ...