Home > Web Front-end > JS Tutorial > How to use JS to get the dates of the last 7 days and the last 3 days

How to use JS to get the dates of the last 7 days and the last 3 days

php中世界最好的语言
Release: 2018-06-07 14:02:31
Original
9067 people have browsed it

This time I will show you how to use JS to get the dates of the last 7 days and the last 3 days. What are the precautions for using JS to get the dates of the last 7 days and the last 3 days. Here is a practical case, let's take a look.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title> JS获取最近三天和最近3天日期</title>
</head>
<body>
<script>
//获取最近7天日期
console.log(getDay(0));//当天日期
console.log(getDay(-7));//7天前日期
//获取最近3天日期
console.log(getDay(0));//当天日期
console.log(getDay(-3));//3天前日期
function getDay(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;
}
</script>
</body>
</html>
Copy after login

Run results:

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Summary of how to use the state object of vuex

react redux starts from scratch

The above is the detailed content of How to use JS to get the dates of the last 7 days and the last 3 days. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template