JQuery获取本地时间和服务器时间
我们都知道直接使用 new Date() 获取到的是访问当前网站的客户机本地的时间,有的时候这个时间有可能因为人为修改,主板电池没电等原因导致获取到的时间不准确。因此,在开发中,需要获取当前时间进行操作,应该直接使用JS获取服务器的时间。
获取本地当前时间(时间戳):
var nowTime = new Date().getTime()/1000;
获取服务器当前时间(时间戳):
// 创建全局变量,也可以是局部的 var serverTime = '' // 通过ajax访问服务器,获取服务器时间 $.ajax({ async: false, type: "GET", success: function(result, status, xhr) { serverTime = new Date( xhr.getResponseHeader("Date")); serverTime = (new Date(serverTime)).getTime() / 1000; }, error: function (a) { } });
时间戳转换为日期格式:
var time, year, month, date, hours, minutes, seconds; time = new Date(); year = time.getFullYear(); //以下是通过三元运算对日期进行处理,小于10的数在前面加上0 month = (time.getMonth() + 1) < 10 ? ("0" + (time.getMonth() + 1)) : (time.getMonth() + 1) date = time.getDate() < 10 ? ("0" + time.getDate()) : time.getDate(); hours = time.getHours() < 10 ? ("0" + time.getHours()) : time.getHours(); minutes = (time.getMinutes() < 10 ? ("0" + time.getMinutes()) : time.getMinutes()); seconds = (time.getSeconds() < 10 ? ("0" + time.getSeconds()) : time.getSeconds()); //拼成自己想要的日期格式,2018-01-15 19:05:33 time = year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds; console.log(time)
封装成方法:
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}` }
分类:
Js/jQuery
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
2020-04-28 Vue 简单实例 地址选配10 - 确认地址 - 下一步
2020-04-28 Vue 简单实例 地址选配9 - 确认地址 - 删除地址