好程序員web前端教程分享Date對象

好程序員web前端教程分享Date對象,什麼是Date對象一個內置對象Date:

類型使用自 UTC(Coordinated Universal Time,國際協調時間)1970 年 1 月 1 日午夜(零時)開始經過的毫秒數來保存日期。Date 類型保存的日期能夠精確到 1970 年 1 月 1日之前或之後的 285616 年。


Date對象怎麼用那?

首先你要獲得Date對象


得到微-信;

var d=new Date( );


在生成日期對象的時候,不傳遞任何參數默認返回當前時間;


var d=new Date( '2015/12/2');



在傳入參數的情況下,獲得的是傳入的時間;


注:這個參數是字符串形式。


一些方法:


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>

<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>

  1. 獲取某個月的天數:

<!doctype html>

<html>

<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>

  1. .計算日期差值

<!doctype html>

<html>

<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='計算日期差距' 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>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章