Date對象和Time對象
Date對象用於操作日期
Time對象用於操作時間
Date對象在使用時前需要先實例化,采用構造函數實例化。
var today=new Date();
// 返回年份
document.write(today.getFullYear());
document.write(
'<br>'
);
// 返回月份,從0到11,0表示1月,11表示12月
document.write(today.getMonth());
document.write(
'<br>'
);
// 返回日期,具體某日
document.write(today.getDate());
document.write(
'<br>'
);
// 返回星期幾
document.write(today.getDay());
document.write(
'<br>'
);
// 返回小時
document.write(today.getHours());
document.write(
'<br>'
);
// 返回分
document.write(today.getMinutes());
document.write(
'<br>'
);
// 返回秒
document.write(today.getSeconds());
document.write(
'<br>'
);
// 返回毫秒,毫秒的范圍從~999
document.write(today.getMilliseconds());
document.write(
'<br>'
);
// 返回時間,這個時間是UTC開始計算的秒數,人看不懂
document.write(today.getTime());
document.write(
'<br>'
);
// toTimeString 將時間轉換成人看得懂的
document.write(today.toTimeString(today.getTime()));
document.write(
'<br>'
);
生成指定的日期
var
lastDate=
new
Date(
'1998-12-12T12:23:45'
);
document.write(lastDate.toDateString(lastDate.getTime()));
document.write(
'<br>'
);
document.write(lastDate.toTimeString(lastDate.getTime()));
document.write(
'<br>'
);
測試題目
1、如何創建Date對象?
答:
- new Date(“month dd,yyyy hh:mm:ss”);
- new Date(“month dd,yyyy”);
- new Date(yyyy,mth,dd,hh,mm,ss);
- new Date(yyyy,mth,dd);
- new Date(ms);
2、Date對象、Number對象、String對象、Math對象的區別是什么?
答:String 對象的屬性和方法用於操作字符串。
Number對象通常用於操作數字。
Math對象用於數學上的計算,如算平方,四舍五入,生成隨機數等等。
Date對象用於操作日期
3、如何使用Date對象生成一個指定的日期?
var
lastDate=
new
Date(
'1998-12-12T12:23:45'
);
document.write(lastDate.toDateString(lastDate.getTime()));
document.write(
'<br>'
);
document.write(lastDate.toTimeString(lastDate.getTime()));
document.write(
'<br>'
);
4、如何計算兩個日期之間的差距?