Reputation: 6095
I want a running clock (Digital) on one of mine Angular 4.3 application.
I tried lots of R&D for that, but didn't get succeed.
also there is no reference of angular ticking clock.
So I tried to Add solution based on java script, but it also not working.
see below code.
startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = this.checkTime(m);
s = this.checkTime(s);
var t = setTimeout(this.startTime, 500);
this.clock = commonSetting.formatedDate(h + ":" + m + ":" + s); // this is the variable that I am showing on the front end.
}
checkTime(i) {
if (i < 10) { i = "0" + i }; // add zero in front of numbers < 10
return i;
}
I don't even know this is good practice or not.
can anyone help me with this?
Upvotes: 0
Views: 3778
Reputation: 6095
Earlier what I did was totally wrong.
Now, My actual scenario has Dropdown and on each dropdown change event, I have to start new clock and have to Stop previous one.
Then, I followed comment of JB Nizet, and I achieved running clock using below code.
TypeScript code
Defined one global Date variable in export class.
time: Date;
Then in Change method of drop down, I Added my solution.
//get current date time, you can set your own Date() over here
var stationdate = new Date(date_from_dropdown_change);
//clear Interval, it's my system requirement
if(this.prevNowPlaying) {
clearInterval(this.prevNowPlaying);
}
// set clock and Interval
this.prevNowPlaying = setInterval(() => {
stationdate = new Date(stationdate.setSeconds(stationdate.getSeconds() + 1));
this.time = stationdate;
}, 1000);
Now, this.Time will get updated per second.
Html
<p class="localtime_p">{{ time | date:'MMM dd,yyyy HH:mm:ss'}}</p>
And currently it's working fine when I posted this answer..
Upvotes: 4
Reputation: 7774
If it were me, I would use Moment.js and set up an interval function in the constructor()
of the component to update the clock
property every second. Then you can display the clock property throughout the component accordingly.
Component
constructor() {
// Runs the enclosed function on a set interval.
setInterval(() => {
this.clock = moment().format('MMMM Do YYYY, h:mm:ss a');
}, 1000) // Updates the time every second.
}
Alternatively you could save a basic timestamp to the property in your component and then use a pipe on the front end like Angular2-moment. I would probably go this route as it affords you more flexibility with the clock property in terms of being able to reuse it elsewhere without messing around with the format too much.
Angular2 Moment Pipe
{{ clock | amLocale:'en' | amDateFormat:'MMMM Do YYYY, h:mm:ss a' }}
Upvotes: 2