JS中日期和时间的获取

时间:2022-09-30 19:22:48

当前时间:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd">
<title>时间格式</title>
<meta http-equiv=Content-Type content="text/html; charset=utf-8">
<html>
<body onLoad="myFunction()" bgcolor="#EEEEEE" text="#6633CC">

<b>
<h2 >
<p>当前时间:</p>

<p id="demo" ></p>
<p id="time0"></p>
<p id="time1"></p>
<p id="time2"></p>
<p id="time3"></p>
<p id="time4"></p>
<p id="time5"></p>
<p id="time6"></p>
<p id="time7"></p>
<p id="time8"></p>
<p id="time9"></p>
</h2>
</b>



<script>
function myFunction()
{
var  wantday=new Date();
var  year=wantday.getFullYear();        //获得当前年份(4位数字);
var month=wantday.getMonth();           //当前月份(从0开始);
var  date=wantday.getDate();            //当月几号;
var  week=wantday.getDay();             //当天星期(数字0-6);
var     h=wantday.getHours();           //当前时(0-24);
var     m=wantday.getMinutes();         //当前分钟;
var     s=wantday.getSeconds();         //当前秒数;
var    ms=wantday.getMilliseconds();    //当前毫秒数;

var    t0=wantday.getYear();            //1900至今的年数(IE8及之前的版本显示与getFullYear相同);
var    t1=wantday.toLocaleString();     //获得当前日期和时间(中国标准时间/GMT+0800)IE/火狐/谷歌显示基本相同,搜狗另类...;
var    t2=wantday.toDateString();       //获得当前日期(本地);
var    t3=wantday.toTimeString();       //获得当前时间(中国标准时间/GMT+0800);
var    t4=wantday.toLocaleTimeString(); //获得当前时间(本地-6位数字);
var    t5=wantday.toLocaleDateString(); //获得当前日期;
var    t6=wantday.toUTCString();        //获得当前国际统一时间(GMT);
var    t7=wantday.getTime();            //获得1900.1.0至现在的毫秒数;
var    t8=wantday.valueOf();            //获得1900.1.0至现在的毫秒数;
var    t9=wantday.getTimezoneOffset();  //获得当前时区与UTC(国际统一时间)的差值,以分钟表示(GMT-当前时区);

//为时、分、秒、补零(不足10时)
h=checktime(h);
m=checktime(m);
s=checktime(s);

function checktime(i){
	if(i<10)
		i="0"+i;
	return i;
}

if(ms<100)     //不足100毫秒时,为毫秒百位补零;
	ms="0"+ms;

switch(week)  //将星期由数字转换为对应中文;
{
	case 1 :week="一";
	break;
	case 2 :week="二";
	break;
	case 3 :week="三";
	break;
	case 4 :week="四";
	break;
	case 5 :week="五";
	break;
	case 6 :week="六";
	break;
	case 0 :week="日";
	break;
}

var time=year+"年"+(month+1)+"月"+date+"日   "+"星期"+week+"   "+h+":"+m+":"+s+":"+ms;

document.getElementById("demo").innerHTML=time;
document.getElementById("time0").innerHTML="1900年至今的年数:"+t0+"年";
document.getElementById("time1").innerHTML=t1;
document.getElementById("time2").innerHTML=t2;
document.getElementById("time3").innerHTML=t3;
document.getElementById("time4").innerHTML=t4;
document.getElementById("time5").innerHTML=t5;
document.getElementById("time6").innerHTML=t6;	
document.getElementById("time7").innerHTML=t7;
document.getElementById("time8").innerHTML=t8;
document.getElementById("time9").innerHTML=t9;
setTimeout("myFunction()",1);
}
</script>
</body>
</html>