How to display Date in Html using angular?
Clash Royale CLAN TAG#URR8PPP
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?
2 Answers
2
You can use Angular DatePipe
to convert the date into the format that you wish to display.
DatePipe
<div> 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 :
( "year": 2018, "month": 8, "day": 7 )
yyyy-MM-dd
setter
datePicker.date
module.ts
providers : [DatePipe]
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
Can you show what object are you getting?
– Amit Chigadani
Aug 7 at 20:07
AddingEmployeeComponent.html:57 ERROR Error: InvalidPipeArgument: 'Unable to convert "[object Object]" into a date' for pipe 'DatePipe'
– BillUser88
Aug 7 at 20:12
Please show the object data that you get by printing
json
. I am not asking the error.– Amit Chigadani
Aug 7 at 20:13
json
If I use what you are saying i am getting this: "year": 2018, "month": 8, "day": 7 But i want to have the date in a proper date format.
– BillUser88
Aug 7 at 20:16
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> date : 'yyyy-MM-dd' </div>
https://ng-bootstrap.github.io/#/components/datepicker/examples#popup
Also, works. Thanks
– BillUser88
Aug 15 at 19:08
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Thanks for the idea, but still it gives me that I cannot convert Object to date. Any more solutions?
– BillUser88
Aug 7 at 20:07