本篇文章主要是对js中日期和计时器的一些总结和小案例
setDate的使用
今天在项目中遇到一个问题如何获取明天的年月日呢?
思路:一开始很自然的想到获取今天的时间+1不就好了吗,但如果是一个月的最后一天怎么办呢?
解决办法:通过setDate来设置时间,再进行获取
var myDate = new Date();
//setDate把Date对象设置为明天的时间
myDate.setDate(myDate.getDate()+1);
var tomorrow_month = myDate.getMonth();
var tomorrow_day = myDate.getDate();
var tomorrow_now = myDate.toLocaleString();
console.log("明天的月份",tomorrow_month);
console.log("明天是哪一天",tomorrow_day);
console.log("明天这时候的日期与时间",tomorrow_now);
一个简单的计时器,setInterval的使用
setInterval传入参数的方法不需要加()
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
window.onload= function(){
var time = document.getElementById("time");
//第一次显示
showtime();
//每1秒执行一次showtime
var timer = setInterval(showtime,1000);
function showtime(){
var data = new Date();
var year = data.getFullYear();
var month= data.getMonth()+1;
var date = data.getDate();
console.log(date)
var hour = data.getHours();
var min = data.getMinutes();
var sec = data.getSeconds();
time.innerHTML=year+'年'+month+'月'+date+"日"+hour+":"+min+":"+sec;
}
}
</script>
</head>
<body>
<p id="time"></p>
</body>
</html>
一个简单的实时验证码,setTimeout的使用
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
#sp{
color: #0000FF;
display:inline-block;
width: 100px;
text-align: center;
background: #eee;
font-weight: bold;
}
</style>
<script>
window.onload = function(){
var txtcode = document.getElementById("txtcode");
var sp = document.getElementById("sp");
var but = document.getElementById("but");
var timeout = false;
var timer = setTimeout(goTime,5000);
function goTime(){
timeout = true;
}
var codelist = ['a','b',1,2,3,4]; // 验证码的字符池
var codes; // 验证码
sp.innerText=createcodes();
console.log(codes)
//生成验证码
function createcodes(){
codes = "";
var x;
for(var i =0;i<4;i++){
x=Math.random()*6;
x=Math.floor(x); //下取整
codes+=codelist[x];
}
return codes.toUpperCase(); //返回大写字符串
}
//点击事件,进行验证和检测超时等功能
but.onclick=function(){
if(!timeout){
if(codes === txtcode.value||codes.toUpperCase() == txtcode.value){
alert("验证成功!")
}else{
alert('失败')
timeout=false;
timer = setTimeout(goTime,10000);
}
}else{
alert("超时")
}
}
sp.onclick=function(){
sp.innerText=createcodes();
timeout=false;
timer = setTimeout(goTime,10000);
}
}
</script>
</head>
<body>
请输入验证码:
<input type="text" name="a" id="txtcode" value="" />
<span id="sp"></span>
<button type="button" id="but">验证</button>
</body>
</html>