可以在html页面内使用JavaScript语句来获取当前日期。最简单的方法是使用{strTime = new Date()}来获取当前日期。
PS:上述语句虽然简单,但是有兼容性问题。相对复杂,但是兼容性好的方法是使用getFullYear、getMonth、getDay语句获取时间。
使用{strTime = new Date()}获取当前日期:
<script langauge='javascript'>function clock()
{
strTime = new Date()
}
</script>
使用getFullYear、getMonth、getDay语句获取当前日期:
效果图:
代码截图:(关键部分用框框标出)
源码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<span id="date"></span><br>
<span id="week"></span>
</div>
<script>
var showDate = document.getElementById('date') // 获取页面元素
var showWeek = document.getElementById('week') // 获取页面元素
var time = new Date()
var year = time.getFullYear() //获取年份
var month = correctDate(time.getMonth() + 1) //获取月份
var day = correctDate(time.getDate()) //获取日期
var date = "今天是" + year + "年" + month + "月" + day + "日"
var week = time.getDay() // 获取星期几,返回的是0/1/2/3/4/5/6 0代表周日
var weeks = [ "星期日","星期一","星期二","星期三","星期四","星期五","星期六"]
var toWeek = weeks[week] // 获取今日星期
showDate.innerHTML = date // 将日期显示在页面
showWeek.innerHTML = toWeek // 将星期显示在页面
/* 这是一个规范数字的函数:
当时间小于10时,在数字前面加上0,统一都是用两个数字表示,
比如3月5日就显示03月05日
*/
function correctDate(date){
if(date<10){
return '0'+date
}
return date
}
</script>
</body>
</html>
<script language="javascript" type="text/javascript">function getFullStringTime(){
var currentDate = new Date()
var strMinute = currentDate.getMinutes()<10?("0"+currentDate.getMinutes()):currentDate.getMinutes()
var strSecond = currentDate.getSeconds()<10?("0"+currentDate.getSeconds()):currentDate.getSeconds()
with(document){
write("现在时间是:","<br>")
if(currentDate.getDay()==0){
write(currentDate.getYear()+1900,"年",currentDate.getMonth()+1,"月",currentDate.getDate(),"日"," ","星期日"," ",currentDate.getHours(),":",strMinute,":",strSecond)
}else{
write(currentDate.getYear()+1900,"年",currentDate.getMonth()+1,"月",currentDate.getDate(),"日"," ","星期日"," ",currentDate.getHours(),":",strMinute,":",strSecond)
}
}
}
getFullStringTime()
</script>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)