Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display Date in Html using angular?

I have two datepickeres in my HTML file using bootstrap and I am trying to display a simple message from this (first selected date) to this (second selected date).

The typescript class is:

 export class Datepicker {
    date: any;
    } 

And the HTML is:

 <div class="form-group">
      <label for="hireDate">Hire Date:</label>
      <form class="form-inline">
        <div class="form-group">
          <div class="input-group">
            <input class="form-control" name="hireDate" id="hireDate" placeholder="yyyy-mm-dd"
                   [(ngModel)]="datePicker.date" ngbDatepicker #d="ngbDatepicker">
            <div class="input-group-append">
              <button class="btn btn-outline-secondary" (click)="d.toggle()" type="button">
                <img src="/assets/calendar-icon.svg" style="width: 1.2rem; height: 1rem; cursor: pointer;"/>
              </button>
            </div>
          </div>
        </div>
      </form>
    </div>
<div>{{datePicker.date}} </div>

But it gives me Object as a result and not the selected date. Any help?

like image 264
BillUser88 Avatar asked Jun 07 '26 08:06

BillUser88


2 Answers

You can use Angular DatePipe to convert the date into the format that you wish to display.

<div> {{datePicker.date | date : 'yyyy-MM-dd'}} </div>

DEMO

EDIT : To convert the date object ({ "year": 2018, "month": 8, "day": 7 }) returned by ngBootstrap to yyyy-MM-dd format, you can do the transformation inside the setter method of datePicker.date property as follows :

module.ts

providers : [DatePipe]

service.ts

export class Datepicker {
  _date: string;
  constructor(private datePipe: DatePipe) {}

  set date(value) {
    let date = new Date(value.year, value.month, value.year);
    this._date= this.datePipe.transform(date, 'yyyy-MM-dd');
  }

  get date() { 
      return this._date
  }
}
like image 67
Amit Chigadani Avatar answered Jun 09 '26 00:06

Amit Chigadani


ng-bootstrap datepicker selection gives you an object like this

Model: {
  "year": 2018,
  "month": 8,
  "day": 9
}

You can write initialize a date object from selected model like this:

<div> {{ new Date(datePicker.date.year, (datePicker.date.month - 1), datePicker.date.day) | date : 'yyyy-MM-dd'}} </div>

https://ng-bootstrap.github.io/#/components/datepicker/examples#popup

like image 44
Mohsin Mehmood Avatar answered Jun 09 '26 00:06

Mohsin Mehmood