Created
December 24, 2024 16:51
-
-
Save ali-master/0874df6b2ab5226d444a5cf96bf56a57 to your computer and use it in GitHub Desktop.
Javascript Server Time handler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ko from 'knockout'; | |
import {getLogger} from 'Util/Logger'; | |
export const serverTimeHandler = { | |
computeTimeOffset(serverTimeString: string): void { | |
const timeOffset = Date.now() - new Date(serverTimeString).valueOf(); | |
this.timeOffset(timeOffset); | |
this.logger.log(`Current backend time is '${serverTimeString}'. Time offset updated to '${this.timeOffset()}' ms`); | |
}, | |
getTimeOffset(): number { | |
if (this.timeOffset() === undefined) { | |
this.logger.warn('Trying to get server/client time offset, but no server time has been set.'); | |
return 0; | |
} | |
return this.timeOffset(); | |
}, | |
logger: getLogger('serverTimeHandler'), | |
timeOffset: ko.observable(undefined) as ko.Observable<number>, | |
/** | |
* Converts a server timestamp to a local timestamp. | |
* @param serverTimestamp the server timestamp to convert | |
* @returns the timestamp adjusted with the client/server time shift | |
*/ | |
toLocalTimestamp(serverTimestamp = Date.now()): number { | |
return serverTimestamp + this.getTimeOffset(); | |
}, | |
/** | |
* Converts a local timestamp to a server timestamp. | |
* @param localTimestamp the local timestamp to convert | |
* @returns the timestamp adjusted with the client/server time shift | |
*/ | |
toServerTimestamp(localTimestamp = Date.now()): number { | |
return localTimestamp - this.getTimeOffset(); | |
}, | |
}; | |
export type ServerTimeHandler = typeof serverTimeHandler; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment