我一直在尝试创建一个倒数计时器,例如几天,小时,分钟,秒,倒数计时器
代码如下:
import {Component, OnInit, ElementRef, Input} from '@angular/core'
import {Observable} from 'rxjs/Rx';
@Component({
selector: 'countdown',
template: `Time to vote {{message}} {{countDown}}`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
@Input() name: string;
message :string;
private future:Date;
private futureString:string;
private diff: any;
@Input() inputDate: Date;
constructor(elm: ElementRef) {
this.futureString = elm.nativeElement.getAttribute('inputDate');
}
dhms(t){
var days, hours, minutes, seconds;
days = Math.floor(t / 86400);
t -= days * 86400;
hours = Math.floor(t / 3600) % 24;
t -= hours * 3600;
minutes = Math.floor(t / 60) % 60;
t -= minutes * 60;
seconds = t % 60;
return [
days + 'd',
hours + 'h',
minutes + 'm',
seconds + 's'
].join(' ');
}
ngOnInit() {
Observable.interval(1000).map((x) => {
this.future = new Date(this.inputDate.toString().replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3"));
this.diff = Math.floor((this.future.getTime() - new Date().getTime()) / 1000);
}).subscribe((x) => {
this.message = this.dhms(this.diff);
});
}
}
是否有一种方法可以对此进行修改,以使其递增计数而不是递减计数? 我已经尝试了一段时间,因此我们将不胜感激。 预先感谢
答案 0 :(得分:1)
更新了StackBlitz Link
简而言之
@Component({
selector: 'countdown',
template: `Time to vote {{message}} {{countDown}}`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
@Input() name: string;
message: string;
private future: Date;
private futureString: string;
private diff: any;
@Input() inputDate: Date;
constructor(elm: ElementRef) {
this.futureString = elm.nativeElement.getAttribute('inputDate');
}
dhms(difference) {
var days, hours, mins, secs;
days = Math.floor(difference / (60 * 60 * 1000 * 24) * 1);
hours = Math.floor((difference % (60 * 60 * 1000 * 24)) / (60 * 60 * 1000) * 1);
mins = Math.floor(((difference % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) / (60 * 1000) * 1);
secs = Math.floor((((difference % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) % (60 * 1000)) / 1000 * 1);
return [
days + 'd',
hours + 'h',
mins + 'm',
secs + 's'
].join(' ');
}
ngOnInit() {
Observable.interval(1000).map((x) => {
this.future = new Date(this.inputDate.toString().replace(/(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3"));
this.diff = Math.floor((new Date().getTime() - this.inputDate.getTime()));
}).subscribe((x) => {
this.message = this.dhms(this.diff);
});
}
}