【问题标题】:'Invalid Date error' appears when trying to find difference between fromTime and toTime尝试查找 fromTime 和 toTime 之间的差异时出现“无效日期错误”
【发布时间】:2019-01-26 09:46:44
【问题描述】:

我有两个离子日期时间选择器(fromTime 和 toTime),以及一种计算它们之间时间差的方法。同样的方法在我使用日期值时有效,但在我使用时间时无效,因为我不断收到“无效日期”错误消息。

我尝试了一些不同的计算时间的建议,但都没有奏效,因此我们将不胜感激。

HTML:

 <ion-grid>
<ion-row>
  <ion-col>
    <ion-datetime class="timeBtn" displayFormat="HH:mm" pickerFormat="HH:mm" minuteValues="00,30" [(ngModel)]="fromTime" (ngModelChange)="timeChange($event, 'fromTime' )" (click)="calculateHours()" placeholder="Select Start Time"></ion-datetime>
  </ion-col>
  <ion-col><ion-icon class="center" name="arrow-round-forward"></ion-icon></ion-col>
  <ion-col>
    <ion-datetime class="timeBtn" displayFormat="HH:mm" pickerFormat="HH:mm" minuteValues="00,30" [(ngModel)]="toTime" (ngModelChange)="timeChange($event, 'toTime' )" (click)="calculateHours()" placeholder="Select End Time"></ion-datetime>
  </ion-col>
</ion-row>
</ion-grid>

<ion-label class="number">{{hoursStr}}</ion-label>  
<ion-label class="center">Total Hours</ion-label>   

TS:

 public fromTime;
 public toTime;  

 constructor(....
 ) {

    let date = new Date();
this.fromTime = date.getHours() + "-" + date.getMinutes();
this.toTime = date.getHours() + "-" + date.getMinutes();

}

  timeChange(e, dateName) {

    this.request[dateName] = new Date(e);
}

  getTime(fromTime, toTime) {
    var start = moment(fromTime);
    var end = moment(toTime);
    var ms = moment(end, "HH:mm").diff(moment(start, " HH:mm"));
    var d = moment.duration(ms);
    var s = Math.floor(d.asHours()) + moment.utc(ms).format(":");
    var t = parseFloat(s);
    return t;
}

   hoursStr = "";
calculateHours() {
    console.log("firedTime", this.fromTime, this.toTime)
    if (this.fromTime && this.toTime) {
        this.hoursStr = "" + this.getTime(this.fromTime, this.toTime)
    }
    console.log(this.hoursStr)
}

【问题讨论】:

    标签: html typescript datetime ionic-framework ionic3


    【解决方案1】:
    moment.duration(this.start.diff(end)).as("minutes")
    

    您的代码中的转换过多:您可以使用时刻对象,并在需要时将它们转换为您需要的格式;否则风险是获取未知格式作为输入

    【讨论】:

    • ..你试过了吗?
    • 嗨,谢谢。是的,我试过了,但我没有工作。错误是因为我在模型中定义的值类型(整数而不是浮点数)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多