简体   繁体   English

在 angular 日期选择器中设置当前日期和默认时间

[英]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, eg Current date: 07-02-2020 and default custom time should be 08:00 AM.我想将默认日期设置为当前日期并使用 Angular 在日期选择器中自定义默认时间,例如当前日期:2020 年 7 月 2 日,默认自定义时间应为 08:00 AM。 How can i achieve this please.请问我怎样才能做到这一点。 Here is my html code which only shows date and time based on value selected.这是我的 html 代码,它仅根据所选值显示日期和时间。

   <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 .component.ts 文件

You need to use moment library for date/time formatting您需要使用moment库进行日期/时间格式化

1-install moment using npm i moment 1-安装时刻使用npm i moment

2-You have to assign value to date_from in your .ts , just like that 2-您必须在.ts中为 date_from 赋值,就像那样

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

<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()您可以根据需要自定义日期,而不是使用 new Date()

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

so you have to import DatePipe所以你必须导入 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并将其添加到 app.module.ts 作为提供者

providers: [
    DatePipe,
    ....
],

read more https://angular.io/api/common/DatePipe阅读更多https://angular.io/api/common/DatePipe

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM