1. 程式人生 > >Js獲取當前的日期和時間

Js獲取當前的日期和時間

<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <title>獲取當前時間</title>
 </head>
 <body>
  <script type="text/javascript">
	/**
	 *獲取當前時間
	 *format=1精確到天
	 *format=2精確到分
	*/
	function getCurrentDate(format) {
	  var now = new Date();
	  var year = now.getFullYear(); //得到年份
	  var month = now.getMonth();//得到月份
	  var date = now.getDate();//得到日期
	  var day = now.getDay();//得到周幾
	  var hour = now.getHours();//得到小時
	  var minu = now.getMinutes();//得到分鐘
	  var sec = now.getSeconds();//得到秒
	  month = month + 1;
	  if (month < 10) month = "0" + month;
	  if (date < 10) date = "0" + date;
	  if (hour < 10) hour = "0" + hour;
	  if (minu < 10) minu = "0" + minu;
	  if (sec < 10) sec = "0" + sec;
	  var time = "";
	  //精確到天
	  if(format==1){
		time = year + "-" + month + "-" + date;
	  }
	  //精確到分
	  else if(format==2){
		time = year + "-" + month + "-" + date+ " " + hour + ":" + minu + ":" + sec;
	  }
	  return time;
	}
	alert(getCurrentDate(2));
  </script>
 </body>
</html>