在前端开发过程中,开发者经常使用newDate()获取当前时间,但是newDate()获取的是当前操作系统的时间,由于user当前电脑时间可以修改,所以不准确。大多数情况下,用户修改当前电脑时间是没有问题的,但是当我们需要根据服务器传来的数据时间和当前时间进行计算时,前端显示就会出错。同时,在前端缓存(localStorage、IndexedDB)中存储需要过期时间的数据(时间)也会出现问题。这时候我们考虑使用服务端提供的时间来代替前端时间。服务器每次与数据交互时都会在响应头中提供时间数据。我们可以使用这些数据来修正前端时间。所以我个人写了一个小工具sync-time。以fetch为例:import{sync,time,date}from'sync-time'asyncfunctiongetJSON(){leturl='https://www.npmjs.com/search?q=';让响应尝试{response=awaitfetch(url);//响应头通常有日期数据console.log(response.headers.get('date'))//使用响应头时间作为服务器时间,调用sync同步数据sync(response.headers.get('date'))}catch(error){}returnresponse.body}getJson()//=>返回一个数字,即校正后的毫秒数getTimetime()//1670345143730//returnsDate,newDate(time())date()//WedDec07202200:46:47GMT+0800(ChinaStandardTime)源码如下:letdiffMillisecond:number=0//获取前端时间constgetCurrentTime=():number=>(newDate()).getTime();//同步时间constsync=(time:Date|string):void=>{//不传时间,直接使用前端时间if(!time){diffMillisecond=0return}//获取UNIX时间戳constsyncTime=timeinstanceofDate?time.getTime():Date.parse(time)//当前值为NaN,直接返回if(Number.isNaN(syncTime)){return}//获取两个时间的差值diffMillisecond=syncTime-getCurrentTime()}//补差价value和getUNIXtimestampconsttime=():number=>getCurrentTime()+diffMillisecondconstdate=():Date=>newDate(time())export{sync,time,date}觉得这篇文章就鼓励一下文章不错,希望大家能给我一些鼓励,帮我在我的github博客下给博客地址加star
