December 5, 2024
Date Formatting in Angular Explained

Formatting Date and Time and Angular, JavaScript, TypeScript (LocalDateTime, NgbDate, DatePicker)

In this simple but comprehensive article, I would teach you how to work with date and time in applications. We would cover the following:

  1. LocalDateTime in Java
  2. DateTime display in HTML Table
  3. DatePicker Control in Angular 9
  4. Setting Current Date in NgbDatePicker
  5. Passing Date in a Post Request
  6. Passing Date in a Put Request
  7. Sending Date in a HTTP Put Request

 

1.  LocalDateTime in Java

The rule of thumb is: anytime you want to use dates in your Java application, use LocalDateTime. For example, the  code below declares appointmentTime as LocalDateTime. In this way, you can split it into date and time if you want. You may also decide to use only the date part.

@Entity
public class Appointment {
    @Id
    private UUID appointmentId;
    private String patientId;
    private LocalDateTime appointmentTime;
    private String status;
}

 

2. DateTime display in HTML Table

In the example below, we take the same DateTime field and split it into date and time columns

<table class="table table-bordered table-striped">
  <thead>
  <tr>
    <th>ID</th>
    <th>Patient ID</th>
    <th>Date</th>
    <th>Time</th>
    <th>Status</th>
    <th>Actions</th>
  </tr>
  </thead>
  <tbody>
  <tr *ngFor="let appointment of appointments">
    <td><span>{{appointment.appointmentId}}</span></td>
    <td><span>{{appointment.patientId}}</span></td>
    <td><span>{{appointment.appointmentTime | date: 'shortDate'}}</span></td>
    <td><span>{{appointment.appointmentTime | date: 'shortTime'}}</span></td>
    <td><span>{{appointment.status}}</span></td>
    
    <td><button type="button" 
                class="btn-info" 
                (click)="openEdit(contentEdit, appointment)">Modify</button></td>
  </tr>
  </tbody>
</table>

 

3. DatePicker Control in Angular 9

You can include DatePicker in your form using the code below:

<input class="form-control" 
       placeholder="yyyy-mm-dd"
       name="appointmentTime" 
       [(ngModel)]="appointmentTime" 
       ngbDatepicker #d="ngbDatepicker">

I’m sure you understand the class attribute and the placeholder attribute. The formControlName helps you bind the value of the control to a field in the data model. The ngbDatepicker identifies the control type while the #d refers to the instance of the datepicker

 

4. Setting Current Date in NgbDatePicker

In the sample application(you can get it on my GitHub Repo), I place the DatePicker in a ngBootstrap modal as shown here:

How to show ngBootstrap modal with Angular

You will have to add the  code to display the current date. This code would be in the event handler for the button click that launches the modal. In this case, it is the open() method.  See the code below:

open(content) {
  const today = new Date();
  this.appointmentTime = new NgbDate(
    today.getFullYear(),
    today.getMonth() + 1,
    today.getDate());
    // ...
    // ...
}

This variable appointmentTime is bound to the Datepicker, so when we assign it’s value, it also modifies the DOM element(which is the Datepicker). Notice that we do three things:

  • we instantiate a normal Date object, today
  • then we used the values of this object to create an NgDate
  • finally, we assign this new NgDate to appointmentTime

Also note that we increment the month by 1. This is because the NgDate months is zero-based, so we need to add 1 to make it up.

 

5. Passing Date in a HTTP Post Request

Now we need to pass this date to the server in a post request when the user clicks on submit. The  appointmentTime is sent together with the patientID which is also entered by the user. See the code below:

onSubmit(f: NgForm) {
  f.value.appointmentTime = new Date(
    f.value.appointmentTime.year,
    f.value.appointmentTime.month,
    f.value.appointmentTime.day);
  this.httpClient.post('http://localhost:8080/appointments/create', f.value)
    .subscribe((result) => {
      this.ngOnInit();
    });
  this.modalService.dismissAll();
 }

In this code, we simply used the values of the appointmentTime in the form f, create a new Date object and assign this date back to the appointmentTime. Finally we bundle the form data (f.value) and send as body of the http post request.

 

6. Displaying Selected Date on Datepicker

The next thing we want to do is to display the date from the selected record in the edit modal. The code below is a markup for the Datepicker for the edit form.

<input class="form-control"
       placeholder="yyyy-mm-dd"
       formControlName="appointmentTime"
       ngbDatepicker #d="ngbDatepicker">

The code for the button opening the edit modal is given below:

openEdit(targetModal, appointment) {
  // ...
  // ...
  const selectedDay = new Date(appointment.appointmentTime);
  this.editForm.patchValue({
    appointmentId: appointment.appointmentId,
    appointmentTime: new NgbDate(selectedDay.getFullYear(),
      selectedDay.getMonth() + 1,
      selectedDay.getDate())
  });
}

In the code above, we first crate a new Date object using the selected appointmentTime. Then we set the values fo appointmentId and appointmentTime inside the patchValue() method of the form. As before, we create and NgbDate object and assign to he appointmentTime. Remember the appointmentTime is bound to the Datepicker. Therefore, when a user modifies the DatePicker, he actually modifies the appointmentTime variable.

 

7. Sending Date in a HTTP PUT Request

Finally, let’s see how send HTTP put request. For my little example, the put request for changing the appointmentTime is executed when the user clicks on Change Time button. This is the code that would run. It follows from previous discussions.

onChangeTime() {
  const newDate = new Date(
    this.editForm.value.appointmentTime.year,
    this.editForm.value.appointmentTime.month - 1,
    this.editForm.value.appointmentTime.day + 1);

  this.httpClient.put('http://localhost:8080/appointments/changeTime/' + this.editForm.value.appointmentId, newDate)
    .subscribe((results) => {
      this.ngOnInit();
      this.modalService.dismissAll();
    });
}

To get these concepts very clear, I would recommend you want the step by step video lesson on my channel. Kindson The Tech Pro on Youtube

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments