JavaScript 计算从今天到 7 天前的日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19910161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:13:13  来源:igfitidea点击:

JavaScript calculating date from today date to 7 days before

javascriptdate

提问by ozil

I am calculating 12 days before date from today date. But it does not return the correct date. For example, for today dat, 11/11/2013 in (mm/dd/yyyy), it returns 10/30/2013 when it should return 10/31/2013.

我从今天开始计算日期前 12 天。但它不会返回正确的日期。例如,对于今天 dat,11/11/2013 in (mm/dd/yyyy),它返回 10/30/2013,而它应该返回 10/31/2013。

Here is the code

这是代码

var d = new Date();
d.setDate(d.getDate() - 12);
d.setMonth(d.getMonth() + 1 - 0);
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
if (curr_month < 10 && curr_date < 10) {
    var parsedDate = "0" + curr_month + "/" + "0" + curr_date + "/" + curr_year;
    alert(parsedDate);
} else if (curr_month < 10 && curr_date > 9) {
    var parsedDate = "0" + curr_month + "/" + curr_date + "/" + curr_year;
    alert(parsedDate);
} else if (curr_month > 9 && curr_date < 10) {
    var parsedDate = curr_month + "/" + "0" + curr_date + "/" + curr_year;
    alert(parsedDate);
} else {
    var parsedDate = curr_month + "/" + curr_date + "/" + curr_year;
    alert(parsedDate);
}

回答by ozil

Problem is solved

问题解决了

var days; // Days you want to subtract
var date = new Date();
var last = new Date(date.getTime() - (days * 24 * 60 * 60 * 1000));
var day =last.getDate();
var month=last.getMonth()+1;
var year=last.getFullYear();

回答by Murtaza Manasawala

You can use the following code to get the date from today date to 7 days before

您可以使用以下代码获取从今天到 7 天前的日期

var date = new Date();
date.setDate(date.getDate() - 7);

var finalDate = date.getDate()+'/'+ (date.getMonth()+1) +'/'+date.getFullYear();

回答by RTW

Pure js one line solution:

纯js一行解决方案:

new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)  // Tue Feb 04 2020 13:50:37 GMT...
  1. new Date() - create Date object from calculated milliseconds time.
  2. Date.now() - gives time in milliseconds from 1970.
  3. 7 (days) * 24 (hours) * 60 (minutes) * 60 (seconds) * 1000 (milliseconds ) = 604800000 or 7 days in milliseconds.
  1. new Date() - 从计算的毫秒时间创建 Date 对象。
  2. Date.now() - 从 1970 年开始以毫秒为单位给出时间。
  3. 7(天)* 24(小时)* 60(分钟)* 60(秒)* 1000(毫秒)= 604800000 或 7 天(以毫秒为单位)。

You can use calculated value if you have no plans to change substracted value, or computed for easy change of substracted amount of days, minutes and so on.

如果您没有计划更改扣除值,或计算后可以轻松更改扣除天数、分钟数等,您可以使用计算值。



If you plan to work more often with dates and time, i recommend to use moment.js

如果您打算更频繁地使用日期和时间,我建议使用moment.js

moment().subtract(7, 'days').calendar()

回答by Schleis

Trying to subtract days is tricky. It would be better to subtract from the timestamp and change the date.

尝试减去天数很棘手。最好从时间戳中减去并更改日期。

To subtract 12 days do:

要减去 12 天,请执行以下操作:

   var d = new Date();
   var ts = d.getTime();
   var twelveDays = ts - (12 * 24 * 60 * 60 * 1000);
   d.setUTCDate(twelveDays);

回答by Christopher Bradley

Updated :)

更新 :)

var timeFrom = (X) => {
    var dates = [];
    for (let I = 0; I < Math.abs(X); I++) {
        dates.push(new Date(new Date().getTime() - ((X >= 0 ? I : (I - I - I)) * 24 * 60 * 60 * 1000)).toLocaleString());
    }
    return dates;
}
console.log(timeFrom(-7)); // Future 7 Days
console.log(timeFrom(7)); // Past 7 Days

Output

输出

[
  '7/26/2019, 3:08:15 PM',
  '7/27/2019, 3:08:15 PM',
  '7/28/2019, 3:08:15 PM',
  '7/29/2019, 3:08:15 PM',
  '7/30/2019, 3:08:15 PM',
  '7/31/2019, 3:08:15 PM',
  '8/1/2019, 3:08:15 PM'
]
[
  '7/26/2019, 3:08:15 PM',
  '7/25/2019, 3:08:15 PM',
  '7/24/2019, 3:08:15 PM',
  '7/23/2019, 3:08:15 PM',
  '7/22/2019, 3:08:15 PM',
  '7/21/2019, 3:08:15 PM',
  '7/20/2019, 3:08:15 PM'
]

回答by Tawfek Mohammed

To get past days as Arrayuse this code

为了让过去的日子如阵列使用此代码

See the console for result

结果见控制台

const GetDays = (d,Mention_today=false)=>{
//Mention today mean the array will have today date 
var DateArray = [];
var days=d;
for(var i=0;i<days;i++){
if(!Mention_today && i==0){i=1;days+=1}
var date = new Date();
var last = new Date(date.getTime() - (i * 24 * 60 * 60 * 1000));
var day =last.getDate();
var month=last.getMonth()+1;
var year=last.getFullYear();
const fulld = (Number(year)+'-'+Number(month)+'-'+Number(day)) // Format date as you like
DateArray.push(fulld);
}
return DateArray;
}

console.log(GetDays(5)) //Will get the past 5 days formated YY-mm-dd

回答by ZaDy Gupta

Date.prototype.addDays = function(days) {
    // Add days to given date
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
}

let today = new Date()

console.log(today.addDays(-7))

回答by Ever Dev

Using dayjs library, we can do it easier.

使用 dayjs 库,我们可以更轻松地做到这一点。

import dayjs from 'dayjs';

const getDate = (prevDays) => {
    const now = dayjs();
    console.log(now.subtract(prevDays, 'day').format('mm-dd-yyyy'));
    return now.subtract(prevDays, 'day').toDate();
}

回答by PrisOneR

Here is best solution.. when X is your day:

这是最好的解决方案.. 当 X 是你的一天:

var dates = [];
for (let i = 0; i < X; i++) {
  var date = new Date();

  var thatDay = date.getDate() - i; //Current Date
  date.setDate(thatDay);
  let day = date.getDate();
  let month = date.getMonth() + 1;
  let year = date
    .getFullYear()
    .toString()
    .substr(-2);

  dates.push(month + '/' + day + '/' + year); //format it as you need
}
//output mm/d/yy

回答by R_J

Here is a function that returns date in past or in future based on below;

这是一个基于以下内容返回过去或将来日期的函数;

If plusMinus = -1 then Past Date
If plusMinus = 1 then Future Date

function getDate(inDays, plusMinus) {
    const today = new Date(); 
    return new Date(today.getFullYear(),
                    today.getMonth(),
                    today.getDate() + (inDays * plusMinus));
}