0

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

2 Answers 2

1

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')

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @ahmed, I want it to show the current date as default, but a static time . e.g 07-02-2020: 8:30AM should show once the page loads. The date part should be dynamic according to the current date but the time should be static
you have to use moment for formatting,check my edit
You are correct, but i want to show the default time, so the user can click and select, but default date and time should be shown on the screen before the user selects from the datepicker. Thanks
0
<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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.