簡體   English   中英

如何從角形材料日期選擇器中獲取當前時間?

[英]How to I get current time from angular material Date picker?

我正在使用角材料datepicker https://material.angular.io/components/select/overview

但這只會返回日期而不是當前時間:2018年5月28日星期一00:00:00 GMT + 0530(IST)

有什么辦法可以從中獲取當前時間嗎?

您可以使用ngModelChange解析日期,然后再將其設置為模型,我建議您使用momentJS以便於日期操作。

在HTML中

 <input [ngModel]="date" (ngModelChange)="onDataChange($event)"  matInput [matDatepicker]="picker" placeholder="Choose a date">

在您的Component.ts中

  onDataChange(newdate) {
    const _ = moment();
    const date = moment(newdate).add({hours: _.hour(), minutes:_.minute() , seconds:_.second()})
    this.date = date.toDate();
    console.log({hours: _.hour(), minutes:_.minute() , seconds:_.second()})
  }

您可以在這里找到完整的解決方案https://stackblitz.com/edit/angular-ecq2lc

角度材料目前未提供時間,您需要手動從timeStamp獲取時間,請嘗試以下操作-

function getTimeFromDate(timestamp) {
  let date = new Date(timestamp * 1000);
  let hours = date.getHours();
  let minutes = date.getMinutes();
  let seconds = date.getSeconds();
  return hours+":"+minutes+":"+seconds
}

let timeStamp = new Date("Mon May 28 2018 00:00:00 GMT+0530 (IST)")
console.log(getTimeFromDate(timeStamp));

現在,重要日期選擇器僅提供當前日期(沒有當前時間),但是正式回購中有一個未解決的問題,因此我們可能會在不久的將來看到一個時間選擇器。

        For Example currenttime = Mon May 28 2018 00:00:00 GMT+0530 (IST)

    Currenttime is an example if  u using current date means just use new Date()  

    //Sample function calling Method 
            Exacttime(){
            this.functionName = this.diffhours(new(currenttime))
            }

            diffhours(currenttime){
               var diff = new Date(currenttime);
                diff .getHours(); // => 9
                diff .getMinutes(); // =>  30
                diff .getSeconds(); // => 51

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM