javascript时间戳和日期字符串相互转换代码(超简单)
javascript时间戳和日期字符串相互转换代码(超简单)
<htmlxmlns="http://www.w3.org/1999/xhtml"> <head> <metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/> <scripttype="text/javascript"> //获取当前时间戳(以s为单位) vartimestamp=Date.parse(newDate()); timestamp=timestamp/1000; //当前时间戳为:1403149534 console.log("当前时间戳为:"+timestamp); //获取某个时间格式的时间戳 varstringTime="2014-07-1010:21:12"; vartimestamp2=Date.parse(newDate(stringTime)); timestamp2=timestamp2/1000; //2014-07-1010:21:12的时间戳为:1404958872 console.log(stringTime+"的时间戳为:"+timestamp2); //将当前时间换成时间格式字符串 vartimestamp3=1403058804; varnewDate=newDate(); newDate.setTime(timestamp3*1000); //WedJun182014 console.log(newDate.toDateString()); //Wed,18Jun201402:33:24GMT console.log(newDate.toGMTString()); //2014-06-18T02:33:24.000Z console.log(newDate.toISOString()); //2014-06-18T02:33:24.000Z console.log(newDate.toJSON()); //2014年6月18日 console.log(newDate.toLocaleDateString()); //2014年6月18日上午10:33:24 console.log(newDate.toLocaleString()); //上午10:33:24 console.log(newDate.toLocaleTimeString()); //WedJun18201410:33:24GMT+0800(中国标准时间) console.log(newDate.toString()); //10:33:24GMT+0800(中国标准时间) console.log(newDate.toTimeString()); //Wed,18Jun201402:33:24GMT console.log(newDate.toUTCString()); Date.prototype.format=function(format){ vardate={ "M+":this.getMonth()+1, "d+":this.getDate(), "h+":this.getHours(), "m+":this.getMinutes(), "s+":this.getSeconds(), "q+":Math.floor((this.getMonth()+3)/3), "S+":this.getMilliseconds() }; if(/(y+)/i.test(format)){ format=format.replace(RegExp.$1,(this.getFullYear()+'').substr(4-RegExp.$1.length)); } for(varkindate){ if(newRegExp("("+k+")").test(format)){ format=format.replace(RegExp.$1,RegExp.$1.length==1 ?date[k]:("00"+date[k]).substr((""+date[k]).length)); } } returnformat; } console.log(newDate.format('yyyy-MM-ddh:m:s')); </script>
以上就是小编为大家带来的javascript时间戳和日期字符串相互转换代码(超简单)全部内容了,希望大家多多支持毛票票~