ozil
ozil

Reputation: 7117

JavaScript calculating date from today date to 7 days before

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

Upvotes: 63

Views: 175995

Answers (12)

ZiiMakc
ZiiMakc

Reputation: 36806

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/

Upvotes: 98

Daniel Shotonwa
Daniel Shotonwa

Reputation: 17

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

Upvotes: -1

Daisy
Daisy

Reputation: 328

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

Upvotes: 3

hriks
hriks

Reputation: 131

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

Upvotes: 5

Tawfeeq
Tawfeeq

Reputation: 157

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

Upvotes: 4

Seymur Abiyev
Seymur Abiyev

Reputation: 21

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

Upvotes: 0

Ever Dev
Ever Dev

Reputation: 2142

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

Upvotes: 0

xchrisbradley
xchrisbradley

Reputation: 493

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

Upvotes: 6

R_J
R_J

Reputation: 1

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

Upvotes: 0

Murtaza Manasawala
Murtaza Manasawala

Reputation: 715

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

Upvotes: 28

ozil
ozil

Reputation: 7117

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

Upvotes: 81

Schleis
Schleis

Reputation: 43690

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

Upvotes: 13

Related Questions