JavaScript 获取时间,时间戳
一. 动态获取js时间
1.方法一:最简单的写法,直接输出时间到页面
<!DOCTYPE html> <html> <head> <title></title> <meta http-equiv=Content-Type content=text/html;charset="utf-8"> <script type="text/javascript"> function getNowTime() { var now = new Date(); var date = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate(); // 年月日 var time = now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds(); // 时分秒 var day = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六")[now.getDay()]; // 星期 document.getElementById("clock").innerHTML = date+" "+time+" "+day; } window.setInterval("getNowTime()", 1000); </script> </head> <body leftmargin="0" topmargin="0" onload="getNowTime()"> <div id="clock"></div> </body> </html>
2、方法二:引用外部js实现多种格式时间
1、Clock.js 代码
function Clock() { var date = new Date(); this.year = date.getFullYear(); this.month = (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1; this.date = date.getDate() < 10 ? "0" + date.getDate() : date.getDate(); this.day = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六")[date.getDay()]; this.hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(); this.minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(); this.second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds(); this.toString = function() { return this.year + "年" + this.month + "月" + this.date + "日 " + this.hour + ":" + this.minute + ":" + this.second + " " + this.day; }; this.toSimpleDate = function() { return this.year + "-" + this.month + "-" + this.date; }; this.toDetailDate = function() { return this.year + "-" + this.month + "-" + this.date + " " + this.hour + ":" + this.minute + ":" + this.second; }; this.display = function(ele) { var clock = new Clock(); ele.innerHTML = clock.toString(); window.setTimeout(function() {clock.display(ele);}, 1000); }; }
2、HTMl 引用代码
注意:10~13 行代码,要放在HTML的最后,否则不会执行!
<html> <head> <title></title> <meta http-equiv=Content-Type content=text/html;charset=utf-8> <script IPT src="js/Clock.js" type=text/javascript></script> </head> <body leftmargin="0" topmargin="0"> <div id="clock"></div> </body> <SCRIPT type=text/javascript> var clock = new Clock(); clock.display(document.getElementById("clock")); </SCRIPT> </html>
二. JS 获取当前的时间戳
获取当前时间的时间戳,有三种方法
第一种方法:
var timestamp = Date.parse(new Date());
结果:1280977330000
第二种方法:
var timestamp = (new Date()).valueOf();
结果:1280977330748
第三种方法:
var timestamp = new Date().getTime();
结果:1280977330748
第一种方法获取的时间戳是把毫秒改成000显示,后两种方法获取了当前毫秒的时间戳。
获取指定时间的时间戳
function getTime(day){ re = /(\d{4})(?:-(\d{1,2})(?:-(\d{1,2}))?)?(?:\s+(\d{1,2}):(\d{1,2}):(\d{1,2}))?/.exec(day); return new Date(re[1],(re[2]||1)-1,re[3]||1,re[4]||0,re[5]||0,re[6]||0).getTime(); } alert(getTime("2013-02-03 10:10:10")); alert(getTime("2013-02-03")); alert(getTime("2013-02")); alert(getTime("2013"));
此博客已暂停维护,博主已搬家至 https://dukec.cn/