admin管理员组

文章数量:1134247

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.

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);
}

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.

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);
}
Share Improve this question edited Nov 11, 2013 at 15:43 Jonathan Naguin 14.8k6 gold badges51 silver badges76 bronze badges asked Nov 11, 2013 at 15:38 ozilozil 7,1179 gold badges35 silver badges60 bronze badges 8
  • 4 one word: moment.js – georg Commented Nov 11, 2013 at 15:39
  • 1 Check your math, 12 days ago is Oct 30. – j08691 Commented Nov 11, 2013 at 15:43
  • Not part of your question but why are you subtracting 0 in d.setMonth(d.getMonth() + 1 - 0); – Schleis Commented Nov 11, 2013 at 15:45
  • 12 days ago it was Oct 31 – ozil Commented Nov 11, 2013 at 15:47
  • 1 @ozil I get that, but you are subtracting 0 which is pointless. It is the same value. Why not just do d.setMonth(d.getMonth() + 1); – Schleis Commented Nov 11, 2013 at 15:52
 |  Show 3 more comments

12 Answers 12

Reset to default 98

Pure js one line solution:

const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)  
  1. new Date() - create Date object from calculated milliseconds time.
  2. Date.now() - gives time in milliseconds from 1970 to now.
  3. 7 (days) * 24 (hours) * 60 (minutes) * 60 (seconds) * 1000 (milliseconds ) = 604800000 (7 days in milliseconds).

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.


Date manipulation library

If you plan to work more often with dates and time, I recommend to use Luxon if you care about timezones or date-fns which is smaller. Compare

import { format, formatDistance, formatRelative, subDays } from 'date-fns'

format(new Date(), "'Today is a' eeee")
//=> "Today is a Friday"

formatDistance(subDays(new Date(), 3), new Date(), { addSuffix: true })
//=> "3 days ago"

formatRelative(subDays(new Date(), 3), new Date())
//=> "last Friday at 7:26 p.m."

Why not moment.js?

Moment.js is considered to be a legacy project in maintenance mode. It is not dead, but it is indeed done. See https://momentjs.com/docs/#/-project-status/

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();

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

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

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

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

To subtract 12 days do:

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

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'
]

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))

To get past days as Array use 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

First: get the current date

 const startingDate = new Date();

Second: get the date you want !!: If you change the startingDate directly by using setDate, it will change this variable.

const sevenDaysBeforeDate = new Date(new Date().setDate(new Date().getDate() - 7));

7 days later

const endDate = new Date(new Date().setDate(new Date().getDate() + 7));

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));
}

Using dayjs library, we can do it easier.

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();
}

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

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

Thanks for the help. I just used a simple function and it worked well

const subtractDayFromDate = (date, days) => {
  const newDate = new Date(date);
  newDate.setDate(newDate.getDate() - days);
  return newDate;
};

本文标签: JavaScript calculating date from today date to 7 days beforeStack Overflow