Reputation: 295
I'm trying to convert my milliseconds to readable Hour, minute, second format. I've tried to do this manually but I'm stuck, and I feel like there should be a simpler way.
Current manually written stopwatch:
ngOnInit(){
//alert(this.datePipe.transform(new Date()));
let timer = Observable.timer(0, 1000);
timer.subscribe(t=>{
this.today = this.datePipe.transform(t);
this.second = t;
if(this.second==60){
this.second = 0;
this.minute += 1;
}else if(this.minute == 60){
this.minute = 0;
this.hour += 1;
}
});
}
Once the t passes 60 sec, seconds wont reset and it will continue to be over 60.
So my question is, is there a simpler way that actually works? I've read this and I don't quite understand how it works in my example DatePipe
HTML
<div class="client-time">
<span>Client time</span>
<br/>
<strong>{{hour}}:{{minute}}:{{second}}</strong>
</div>
</footer>
Basically I'm trying to show how long a user has been on the page.
Upvotes: 5
Views: 11542
Reputation: 5457
Here is a simple version, showing the time in seconds:
Component:
private timer;
private counter: Date;
ngOnInit() {
this.timer = Observable.timer(0,1000)
.subscribe(t => {
this.counter = new Date(0,0,0,0,0,0);
this.counter.setSeconds(t);
});
}
ngOnDestroy(){
this.timer.unsubscribe();
}
Template:
<div class="client-time">
<span>Client time</span><br/>
<strong>{{counter | date:'HH:mm:ss'}} seconds</strong>
</div>
Upvotes: 5
Reputation: 1802
To use DatePipe in combination with time take a look at the following:
start = new Date(0,0,0);
ngOnInit() {
Observable.interval(1000)
.startWith(0)
.subscribe(t => {
this.start = new Date(0, 0, 0);
this.start.setSeconds(t);
});
}
And the HTML should be
{{start | date:'HH:mm:ss'}}
Upvotes: 6