我有两个离子日期时间选择器(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)
}
答案 0 :(得分:0)
moment.duration(this.start.diff(end)).as("minutes")
您的代码中的转换太多:您可以处理矩对象,并在需要时将其转换为所需的格式;否则风险就是获取未知格式作为输入