As the title says, I want the current system time.
I know that using Date()
can give me the current time, but that isn't necessarily the system time so it doesn't help.
I know I can use http request for getting the system time from some backend service, but the problem is that I want the system time to be updated dynamically (if system time changes - I expect my web page to change the time even if I don't refresh the page).
So if there's a way to achieve this using angular only - it will be much easier.
Is it possible to do so?
Example:
I'm using Linux machine, and now I set the current date to be 1 Feb 2022, 03:12:20 like this:
sudo date -s "1 FEB 2022 03:12:20"
So now I expect my web page to display the same date and time - 1 FEB 2022 03:12:20
CodePudding user response:
you can use a rxjs operator and map
date$=timer(0,1000).pipe(map(_=>new Date()))
{{date$|async}}
But this only give you the date in the client. If you want the date in server you need make a call to the server to correct
So you can has some like
incr:number=0;
date$=timer(0,1000).pipe(
switchMap((i:number)=>{
if (i==0) //you can indicate here when you want "check"
//the date in server,e.g. each 10 seconds
{
return this.service.getDate().pipe(tap(x=>{
this.incr=x.getTime()-new Date().getTime()}))
}
return of(new Date(new Date().getTime() this.incr))
}))
CodePudding user response:
didn't test it, but new Date()
should always give you the system time, meaning that you could just get new Date()
every second.
this roughly translates to:
If no arguments are given, the constructor creates a date object with the date and time of the current system time zone
so the solution would be:
document.setInterval(() => console.info(new Date()), 1000);
or maybe more angularly (using rxjs instead of vanilla)
timer(1000).subscribe(() => console.info(new Date());