Francis
Francis

Reputation: 53

Setting current date and default time in angular datepicker

I want to set the default date to current date and customize default time in a datepicker using Angular, e.g Current date: 07-02-2020 and default custom time should be 08:00 AM. How can i achieve this please. Here is my html code which only shows date and time based on value selected.

   <label class="col-sm-12 col-md-8 form-control-label  ml-2" for="date_from">{{'From Date' | 
  translate}} <span class="danger">*</span>:</label>
                <div class="col-md-12">
                    <input type="datetime-local" [(ngModel)]="leaveList.date_from" 
  [max]="leaveList.date_to" class="form-control input-md" id="date_from" 
                    name="date_from" (change)="onChangeDate()"  max="9999-12-31">
                </div>

.component.ts file

Upvotes: 0

Views: 3423

Answers (2)

Mafei
Mafei

Reputation: 3801

<input required class="form-control" [(ngModel)]="myDate" type="datetime-local" name="myDate" id="myDate"/>

you can customize the date as you want instead of using new Date()

this.myDate = this.datepipe.transform(new Date(), 'yyyy-MM-ddThh:mm'),

so you have to import DatePipe

import {DatePipe} from '@angular/common'

and initialize in the constructor

constructor(public datepipe: DatePipe){
}

and also add it int the app.module.ts as a provider

providers: [
    DatePipe,
    ....
],

read more https://angular.io/api/common/DatePipe

Upvotes: 0

Ahmed Abdelfattah
Ahmed Abdelfattah

Reputation: 577

You need to use moment library for date/time formatting

1-install moment using npm i moment

2-You have to assign value to date_from in your .ts, just like that

leaveList.date_from = moment().format('MM-DD-YYYY 8:30A')

Upvotes: 1

Related Questions