You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

useServerTime.ts 1.4 kB

11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. /*
  2. * @Author: 赵伟
  3. * @Date: 2024-10-10 08:51:41
  4. * @Description: 服务器时间 hook
  5. */
  6. import { getSeverTimeReq } from '@/services/experiment';
  7. import { to } from '@/utils/promise';
  8. import { useCallback, useEffect, useState } from 'react';
  9. let globalTimeOffset: number | undefined = undefined;
  10. export const globalGetSeverTime = async () => {
  11. const requestStartTime = Date.now();
  12. const [res] = await to(getSeverTimeReq());
  13. const requestEndTime = Date.now();
  14. const requestDuration = (requestEndTime - requestStartTime) / 2;
  15. if (res && res.data) {
  16. const serverDate = new Date(res.data);
  17. const timeOffset = serverDate.getTime() + requestDuration - requestEndTime;
  18. globalTimeOffset = timeOffset;
  19. return timeOffset;
  20. }
  21. };
  22. export const now = () => {
  23. return new Date(Date.now() + (globalTimeOffset ?? 0));
  24. };
  25. /** 获取服务器时间 */
  26. export function useServerTime() {
  27. const [timeOffset, setTimeOffset] = useState<number>(globalTimeOffset ?? 0);
  28. useEffect(() => {
  29. const getSeverTime = async () => {
  30. const [res] = await to(globalGetSeverTime());
  31. if (res) {
  32. setTimeOffset(res);
  33. }
  34. };
  35. // 获取服务器时间,防止第一次加载时,请求失败
  36. if (!globalTimeOffset) {
  37. getSeverTime();
  38. }
  39. }, []);
  40. const now = useCallback(() => {
  41. return new Date(Date.now() + timeOffset);
  42. }, [timeOffset]);
  43. return [now] as const;
  44. }