开发中经常遇到获取时间的业务,将常用的方法做个笔记记录下。
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script>
function getRecentDay(day){
var today = new Date();
var targetday_milliseconds=today.getTime() + 1000*60*60*24*day;
today.setTime(targetday_milliseconds);
var tYear = today.getFullYear();
var tMonth = today.getMonth();
var tDate = today.getDate();
tMonth = doHandleMonth(tMonth + 1);
tDate = doHandleMonth(tDate);
return tYear+"-"+tMonth+"-"+tDate;
}
function doHandleMonth(month){
var m = month;
if(month.toString().length == 1){
m = "0" + month;
}
return m;
}
console.log("半年前:"+getRecentDay(-180));
console.log("三月前:"+getRecentDay(-90));
console.log("一月前:"+getRecentDay(-30));
console.log("昨天:"+getRecentDay(-1));
console.log("今天:"+getRecentDay(0));
console.log("明天:"+getRecentDay(1));
console.log("后天:"+getRecentDay(2));
console.log("一月后:"+getRecentDay(30));
console.log("三月后:"+getRecentDay(90));
console.log("半年后:"+getRecentDay(180));
</script>
</body>
</html>
原文作者技术博客:https://www.jianshu.com/u/ac4daaeecdfe
网友评论