好程序員web前端教程分享Date對象,什麼是Date對象一個內置對象Date:html
類型使用自 UTC(Coordinated Universal Time,國際協調時間)1970 年 1 月 1 日午夜(零時)開始通過的毫秒數來保存日期。Date 類型保存的日期可以精確到 1970 年 1 月 1日以前或以後的 285616 年。前端
Date對象怎麼用那?程序員
首先你要得到Date對象web
獲得微-信;htm
var d=new Date( );對象
在生成日期對象的時候,不傳遞任何參數默認返回當前時間;blog
var d=new Date( '2015/12/2');教程
在傳入參數的狀況下,得到的是傳入的時間;ip
注:這個參數是字符串形式。字符串
一些方法:
1.d.getFullYear() 獲取當前的年份。|| d.setFullYear(2012) 返回1970年1月1日到設定時間毫秒數;
2.d.getMonth() 獲取當前的月份(注:一個小BUG,當前的月份從0開始)||d.setMonth(9)返回1970年1月1日到當前年份的設定月份的毫秒數;
3.d.getDate()獲取當前的日期 ||d.setDate() 同上;
4. getHours() 獲取時
getMinutes() 獲取分鐘
getSeconds() 獲取秒
各個機器獲取的時間不一樣,由於該方法返回的是本機的時間;並非國際標準時間;
5.日期的修改;
Date.parse("2015-08-24");獲取1970年到設定時間的毫秒數;
d.getTime();獲取1970年到當前時間的毫秒數;
d.setTime()
new Date(time)
建立一個日期對象,並指定時間 能夠指定毫秒數
或者修改time屬性, var d = new Date(); d.setTime(56521211021);
案例:
1.將日期格式化
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
</body>
<script>
function geshihua() {
var d = new Date();
var year = d.getFullYear();
var Month = d.getMonth() + 1;
var day = d.getDate();
var str = '當前時間是:' + year + '年' + Month + '月' + day + '日'
document.write(str);
}
geshihua()
</script>
</html>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function days(year, month) {
var str = year + '/' + month + '/1';
var d = new Date(str);
var Month = d.getMonth();
var MonthMin = d.setMonth(Month);
var MonthMin2 = d.setMonth(Month + 1);
var MonthDay = MonthMin2 - MonthMin
alert(MonthDay / 24 / 60 / 60 / 1000)
}
days('2014', '2')
</script>
</head>
<body>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.btn{
background:none;
border: 1px solid #b6b6b6;
display: block;
height: 40px;
margin: 40px auto;
}
</style>
</head>
<body>
<div id="div1">
<input type="text" placeholder='起始年份'>
<input type="text" placeholder='起始月份'>
<input type="text" placeholder='起始日'>||
<input type="text" placeholder='終止年份'>
<input type="text" placeholder='終止月份'>
<input type="text" placeholder='終止日'>
</div>
<input type="button" value='計算日期差距' class="btn" onclick='jisuanriqi()'>
</body>
<script>
function jisuanriqi() {
var oDiv = document.getElementById('div1');
var aInput = oDiv.getElementsByTagName('input');
var qishiArr = [];
var zhongzhiArr = [];
for (var i = 0; i < aInput.length; i++) {
if (i < 3) {
qishiArr[i] = aInput[i].value;
} else {
zhongzhiArr[i] = aInput[i].value;
}
}
var str1 = qishiArr.join('/');
var str2 = zhongzhiArr.join('/');
var d1 = new Date(str1);
var d2 = new Date(str2);
alert(d1 + ":" + d2)
var days = Math.abs(d1.getTime() - d2.getTime()) / 1000 / 24 / 60 / 60;
alert(days)
}
</script>
</html>