一、JavaScript获取当前时间戳的方法
第一种方法:
var timestamp = Date.parse(new Date());
结果:1280977330000
第二种方法:
var timestamp = (new Date()).valueOf();
结果:1280977330748
第三种方法:
var timestamp=new Date().getTime();
结果:1280977330748
第一种:获取的时间戳是把毫秒改成000显示,第二种和第三种是获取了当前毫秒的时间戳。
二、URL时间戳作用及用法
作用:为了防止浏览器缓存。
URL后面添加随机数或时间戳通常用于防止浏览器(客户端)缓存页面。 浏览器缓存是基于URL进行缓存的,如果页面允许缓存,则在缓存时效前再次访问相同的URL,浏览器就不会再次发送请求到服务器端,而是直接从缓存中获取指定资源。
而当URL 的末尾追加了随机数或时间戳,就会保证每次都会实际生成新请求且 Web 服务器不会尝试缓存来自服务器的响应。
用法:
//解决浏览器缓存 function timestamp(url){ // var getTimestamp=Math.random(); var getTimestamp=new Date().getTime(); if(url.indexOf("?")>-1){ url=url+"×tamp="+getTimestamp }else{ url=url+"?timestamp="+getTimestamp } return url; }
三、前端JS对timestamp固定格式转换的方法封装
var value={ time: 1461575459000 }; Date.prototype.format = function(format) { var o = { "M+" : this.getMonth() + 1,// month "d+" : this.getDate(),// day "h+" : this.getHours(),// hour "m+" : this.getMinutes(),// minute "s+" : this.getSeconds(),// second "q+" : Math.floor((this.getMonth() + 3) / 3),// quarter "S" : this.getMilliseconds() // millisecond }; if (/(y+)/.test(format) || /(Y+)/.test(format)) { format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); } for ( var k in o) { if (new RegExp("(" + k + ")").test(format)) { format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)); } } return format; };
用法:
(new Date(parseFloat(value.time))).format("yyyy-MM-dd hh:mm:ss");
结果:2016-04-25 17:10:59