js學習三-日期Date

EpisodeOne發表於2016-05-15
Date
date = new Date()
date.getXXX()

date.setXXX()
瀏覽器會智慧計算
new Date(2016,2,0)        2016-2-29

程式碼:

<span style="font-size:14px;"><!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Date</title>
</head>
<body>
	<script type="text/javascript">
		var date = new Date();
		console.log('date');
		console.log(date);
		// Sun May 15 2016 15:00:33 GMT+0800 (China Standard Time)
		function padding(number) {
			// 補零
			return number < 10? '0'+number:''+number;
		}
		function format(date) {
			//格式化
			return date.getFullYear()+'-'+padding(date.getMonth()+1)+'-'+padding(date.getDate())+' '+padding(date.getHours())+':'+padding(date.getMinutes())+':'+padding(date.getSeconds());
		}
		function getDays(year, month) {
			var date = new Date(year, month, 0);
			console.log('date');
			console.log(date);
			// Mon Feb 29 2016 00:00:00 GMT+0800 (China Standard Time)
			return date.getDate();
		}
		console.log(format(date));
		// 2016-05-15 15:14:18

		date.setDate(35);
		console.log(format(date));
		//2016-06-04 15:19:04
		date.setHours(100);
		console.log(format(date));
		// 2016-06-08 04:19:04
		console.log(getDays(2016,2)+'天')
		//29天
	</script>
</body>
</html></span>


相關文章