如何创建一个倒计时计时器角度 5



我一直在尝试创建一个倒数计时器,例如天小时分钟秒,我得到了一个倒数计时器

这是代码:

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);
});
}
}

有没有办法修改它以使其向上计数而不是向下计数? 我已经尝试了一段时间,所以任何帮助将不胜感激。 提前致谢

更新了StackBlitz链接

简而言之

@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);
});

}
}

最新更新