【问题标题】:How to I get current time from angular material Date picker?如何从角度材料日期选择器获取当前时间?
【发布时间】:2018-11-06 20:52:03
【问题描述】:

我正在使用角度材料日期选择器 https://material.angular.io/components/select/overview

但这仅返回日期而不是当前时间: 2018 年 5 月 28 日星期一 00:00:00 GMT+0530 (IST)

有什么方法可以从中获取当前时间吗?

【问题讨论】:

    标签: javascript angular typescript angular-material angular5


    【解决方案1】:

    角材质现在不提供时间你需要手动从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));
    

    【讨论】:

      【解决方案2】:

      目前,材料日期选择器仅提供当前日期(没有当前时间),但官方 repo 中有一个未解决的问题,因此我们可能会在不久的将来看到时间选择器。

      【讨论】:

        【解决方案3】:

        您可以使用 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

        【讨论】:

        • 谢谢它是完美的! :)
        【解决方案4】:
                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
        
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-09-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-05-31
          • 2018-07-16
          • 1970-01-01
          • 2020-09-23
          相关资源
          最近更新 更多