关于项目中使用时间的问题

项目中使用的时间

前端获取时间

获取JavaScript时间戳函数的5种方法,你都了解吗?(https://zhuanlan.zhihu.com/p/652330526

复制代码
前端获取本地时间戳
 console.log(Date.now())//1642471441587

时间戳在线转化

Date.now()获取的是电脑本地 当电脑本地时间调整,或跟新不及时,获取错误时间。

举例:

电脑A启动vue项目 ,代码中使用了Date.now();

电脑B打开访问vue项目。 当代码运行到Date.now()时,获取到的时是B电脑的时间。

优化:

JQuery获取服务器时间

复制代码
  $.ajax({
    async: false,
    type: "GET",
    success: function(result, status, xhr) {
      var serverTime = new Date( xhr.getResponseHeader("Date"));
        serverTime = (new Date(serverTime)).getTime() / 1000;
        console.log(serverTime)//获取到软件所运行的服务器处获取的时间
    },
    error: function (a) {

    }
});

举例:

电脑A启动vue项目 ,代码中使用了Date.now();

电脑B打开访问vue项目。 当代码运行到Date.now()时,获取到的时是A电脑的时间。

附:时间戳转常用时间格式

复制代码
    /**
       * @description 时间戳转常用时间格式
        *@param {String}  时间戳
        * @return 2020-11-9 14:21:35 格式时间
     */

function filterTime(time) {
      var date = new Date(time)
      var Y = date.getFullYear()
      var M = date.getMonth() + 1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1 
      var D = date.getDate()
      var hours = date.getHours() < 10 ? ("0" + date.getHours()) : date.getHours();
      var minutes = (date.getMinutes() < 10 ? ("0" + date.getMinutes()) : date.getMinutes());
      var seconds = (date.getSeconds() < 10 ? ("0" + date.getSeconds()) : date.getSeconds());
      return `${Y}-${M}-${D} ${hours}:${minutes}:${seconds}`
}
相关推荐
专业抄代码选手8 小时前
08|Fiber 上的 `useState`:状态终于属于具体组件
前端·javascript·react.js
默_笙8 小时前
😭 Vibe Coding 翻车实录:AI 编程为什么必须先写"剧本"
前端·javascript
lerhxx9 小时前
我用 R3F 手搓了一个能走进去的 3D 迷宫简历(上):从选型架构到迷宫生成算法
前端·javascript·three.js
鹏多多14 小时前
PC 网站接入微信登录,这 10 个坑我替你踩完了!
前端·javascript·vue.js
用户2986985301415 小时前
React 中 HTML 内容转 Word 文档的实现方案
javascript·react.js·html
mONESY15 小时前
我用 Next.js 16 + Supabase 从零做了个「背单词」H5 应用
javascript
boooooooom15 小时前
手把手做一个图 RAG 烹饪问答系统:Neo4j + Milvus + LLM 的工程实践
前端·javascript·后端
染指111018 小时前
103.RAG-LLamaIndex后端rag问答-聊天接口
前端·javascript·vue.js·人工智能
单线程_011 天前
从案例分析 Vue3 Tokenizer+Parser 源码三
前端·javascript·vue.js
小磊哥er1 天前
深入解构Claude Code - 第 8 篇 · 数据放哪、钱怎么算
javascript·ai编程