59

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);
}
Jonathan Naguin
  • 14,526
  • 6
  • 46
  • 75
ozil
  • 6,930
  • 9
  • 33
  • 56

12 Answers12

88

Pure js one line solution:

const sevenDaysAgo: Date = 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, date-fns which is smaller or dayjs which is even smaller but with less features. 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/

ZiiMakc
  • 31,187
  • 24
  • 65
  • 105
80

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();
ozil
  • 6,930
  • 9
  • 33
  • 56
28

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

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);
Schleis
  • 41,516
  • 7
  • 68
  • 87
  • 1
    I am getting an error on var ts = d.UTC(); I am using java script 1.9.2 – ozil Nov 12 '13 at 13:10
  • Sorry wrong method. It should be getTime() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime – Schleis Nov 12 '13 at 14:04
6

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'
]
xchrisbradley
  • 416
  • 6
  • 21
5

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))
hriks
  • 131
  • 3
  • 2
4

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
Tawfeeq
  • 147
  • 1
  • 1
  • 9
3

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));
Daisy
  • 288
  • 3
  • 8
0

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));
}
rioV8
  • 24,506
  • 3
  • 32
  • 49
R_J
  • 1
  • 3
  • this is incorrect because it will use illegal `day` argument values (range [1..31]) and for some months even less then 31, the trick with the `ms` is the only valid one (ozil) – rioV8 Aug 31 '18 at 21:09
  • Appreciate your feedback @rioV8 If I understood your concern correctly, then I want to call out that Month and Date itself is determined from Date object, like today.getMonth() will follow range [0-11] as it's coming from today which is a date object. Correct me if I am wrong. – R_J Sep 04 '18 at 18:55
  • yes but if `getDate()` returns 1 and you subtract 5 days you set the new day parameter to `-4` and that is not allowed and leads to indeterminate behavior and is implementation dependent. – rioV8 Sep 04 '18 at 20:19
  • I don't think that's correct. If you run below code in console, it will return proper value; `new Date(today.getFullYear(), today.getMonth(), today.getDate() - 45);` – R_J Sep 26 '18 at 22:07
0

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();
}
Ever Dev
  • 1,882
  • 2
  • 14
  • 34
0

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

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

  • 1
    This does not really answer the original question anymore than the other answers, and you do not provide an explanation of why your code is more useful than the accepted answers. – Scornwell Aug 06 '21 at 13:26