1. 程式人生 > >JavaScript如何獲取日期

JavaScript如何獲取日期

(1)
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<div id="box"></div>
	<script type="text/javascript">
		showtime();
		function showtime(){
		var date=new Date();
		//獲取年,月,日
		var year=date.getFullYear();
        var month=date.getMonth()+1;
        var day=date.getDate();
        //console.log(year,month,day);
        //獲取時,分,秒
        var hour=date.getHours();
        var minute=date.getMinutes();
        var second=date.getSeconds();

        if (hour<10) {
        	hour='0'+hour;
        }
        if (minute<10) {
        	minute='0'+minute;
        }
        if (second<10) {
        	second='0'+second;
        }


        //console.log(hour,minute,second);
        var time=year+'/'+month+'/'+day+''+hour+':'+minute+':'+second;
        document.getElementById('box').innerHTML=time;
        setInterval(showtime,1000);//每秒重新整理一次
       }
	</script>
</body>
</html>
(2)
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<div id="box"></div>
	<script type="text/javascript">
	          //函式呼叫
		var o=document.getElementById('box');
		function showTime(){
			//獲取年,月,日
		var date = new Date;
		var year=date.getFullYear();
		var month=date.getMonth()+1;
		var day=date.getDate();
		//獲取時,分,秒
		var hour=date.getHours();
		var minute=date.getMinutes();
		var second=date.getSeconds();
            year=add(year);
            month=add(month);
            day=add(day);
            hour=add(hour);
            minute=add(minute);
            second=add(second);

		time=year+'/'+month+'/'+day+' '+hour+':'+minute+':'+second;
		o.innerHTML=time;
		}
		function add(num){
               if (num<10) {
               	    num='0'+num;
               }
               return num;
		}
         showTime();
         setInterval(showTime,1000);
   </script>
</body>
</html>