javascript 日期对象学习

时间:2022-02-03 20:19:01

javascript 日期对象学习

.html代码如下:

</pre><pre name="code" class="html"><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>日期对象</title>
<style type="text/css">

</style>
<script type="text/javascript">
function changeColor(){
var myDate = new Date();
var year = myDate.getFullYear();
var month = myDate.getMonth();
var day = myDate.getDate();
var hour = myDate.getHours();
var minute = myDate.getMinutes();
var second = myDate.getSeconds();
var week = myDate.getDay();
var str = "当前日期:"+year+"年"+(month+1)+"月";
str += day+"日"+hour+":"+minute+":"+second+":";
str += "今天是星期"+week;
document.getElementById("mess1").innerText = "toDateString()方法:"+myDate.toDateString();
document.getElementById("mess2").innerText ="toLocaleDateString()方法:"+ myDate.toLocaleDateString();
document.getElementById("mess3").innerText = str;
}
</script>
</head>
<body>

<input type="button" value="日期对象get方法" onclick="changeColor()"/><br/>
<span id="mess1"></span><br/>
<span id="mess2"></span><br/>
<span id="mess3"></span>
</body>
</html>

效果如下:

javascript 日期对象学习

用日期对象实现下拉效果,代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>出生日期</title>

</head>
<body>

<select>
<script type="text/javascript">
var date = new Date();
var year = date.getFullYear();
for(var i = 1900 ; i <= year ; i++){
if(i == year){
document.write("<option selected>"+i+"</option>");
}else{
document.write("<option>"+i+"</option>");
}
}
</script>

</select>年
<select>
<script type="text/javascript">
var date = new Date();
var month = date.getMonth()+1;
var str = "";
for(var i = 1 ; i <=12;i++){
if(i == month){
str += "<option selected>"+i+"</option>";
}else{
str +="<option>"+i+"</option>";
}
}
document.write(str);
</script>
</select>月

</body>
</html>

注意用document.write()方法实现html控件的加入!

效果如下:

javascript 日期对象学习