Determine the date 7 days before today using JavaScript

I've been trying to calculate the date that is 12 days before today's date, but I'm running into an issue where it's not returning the correct result. For instance, if today is November 11, 2013 (mm/dd/yyyy), the code returns October 30, 2013 instead of the expected October 31, 2013.

Here is the code snippet I am using:

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

Answer №1

Simplified solution using pure JavaScript:

const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)  
  1. new Date() - creates a Date object based on calculated milliseconds.
  2. Date.now() - provides the current time in milliseconds since 1970.
  3. 7 days * 24 hours * 60 minutes * 60 seconds * 1000 milliseconds = 604800000 (equivalent to 7 days in milliseconds).

If you don't plan to change the subtracted value, you can use the calculated constant directly. Alternatively, compute it for easier adjustment of the number of days, minutes, etc.


Recommended Date Manipulation Libraries

For frequent date and time operations, consider using Luxon if you require timezone support or opt for the lighter date-fns. Compare them here.

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."

Transition away from moment.js

The maintenance of Moment.js is winding down, with the project being labeled as legacy. While not officially obsolete, it's recommended to explore alternative libraries. More details can be found here.

Answer №2

Issue successfully resolved

let daysToSubtract; // Specify number of days to subtract
const currentDate = new Date();
const previousDate = new Date(currentDate.getTime() - (daysToSubtract * 24 * 60 * 60 * 1000));
const dayOfMonth = previousDate.getDate();
const monthOfYear = previousDate.getMonth()+1;
const yearValue = previousDate.getFullYear();

Answer №3

Here is the code snippet to retrieve the date from today to 7 days prior

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

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

Answer №4

When attempting to deduct days, it can be a bit complicated. A more effective approach would involve subtracting from the timestamp and adjusting the date accordingly.

If you want to subtract 12 days, follow these steps:

   let currentDate = new Date();
   let currentTimestamp = currentDate.getTime();
   let twelveDaysAgo = currentTimestamp - (12 * 24 * 60 * 60 * 1000);
   currentDate.setUTCDate(twelveDaysAgo);

Answer №5

Updated and ready to go!

let calculateTime = (X) => {
    let timeArray = [];
    for (let count = 0; count < Math.abs(X); count++) {
        timeArray.push(new Date(new Date().getTime() - ((X >= 0 ? count : (count - count - count)) * 24 * 60 * 60 * 1000)).toLocaleString());
    }
    return timeArray;
}
console.log(calculateTime(-7)); // Next 7 Days
console.log(calculateTime(7)); // Previous 7 Days

Results

[
  '8/1/2019, 3:08:15 PM',
  '7/31/2019, 3:08:15 PM',
  '7/30/2019, 3:08:15 PM',
  '7/29/2019, 3:08:15 PM',
  '7/28/2019, 3:08:15 PM',
  '7/27/2019, 3:08:15 PM',
  '7/26/2019, 3:08:15 PM'
]
[
  '8/1/2019, 3:08:15 PM',
  '8/2/2019, 3:08:15 PM',
  '8/3/2019, 3:08:15 PM',
  '8/4/2019, 3:08:15 PM',
  '8/5/2019, 3:08:15 PM',
  '8/6/2019, 3:08:15 PM',
  '8/7/2019, 3:08:15 PM'
]

Answer №6

Date.prototype.subtractDays = function(days) {
    // Subtract days from given date
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() - days);
    return date;
}

let today = new Date()

console.log(today.subtractDays(7))

Answer №7

If you need to retrieve the past days as an array, you can utilize this code snippet:

Check the console for the output

const GetDays = (d, Mention_today = false) => {
//Mention today means the array will include today's 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)); // Customize date format here
DateArray.push(fulld);
}
return DateArray;
}

console.log(GetDays(5)) // Outputs past 5 days in the format YY-mm-dd

Answer №8

Step One: Retrieve the current date.

 const currentDate = new Date();

Step Two: Determine the desired date. Note: Modifying the currentDate using setDate will impact this variable.

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

Date set for 7 days in the future

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

Answer №9

Check out this handy function that can give you a date in either the past or future:

If plusMinus = -1, it will give you a date in the past.
If plusMinus = 1, it will give you a date in the future.

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

Answer №10

Make your life simpler with the dayjs library.

import dayjs from 'dayjs';

const findDate = (pastDays) => {
    const current = dayjs();
    console.log(current.subtract(pastDays, 'day').format('mm-dd-yyyy'));
    return current.subtract(pastDays, 'day').toDate();
}

Answer №11

Looking for the ideal solution? When X represents your day:

let calendarDates = [];
for (let count = 0; count < X; count++) {
  let currentDate = new Date();

  let targetDay = currentDate.getDate() - count; //Current Date
  currentDate.setDate(targetDay);
  let dayOfMonth = currentDate.getDate();
  let monthOfYear = currentDate.getMonth() + 1;
  let yearShort = currentDate
    .getFullYear()
    .toString()
    .substr(-2);

  calendarDates.push(monthOfYear + '/' + dayOfMonth + '/' + yearShort); //customize format as needed
}
//output mm/d/yy

Answer №12

Appreciate the assistance. A basic function did the trick for me

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to set a button as default clicked in an Array

I have a collection that stores languages and their boolean values. My goal is to automatically set buttons to be clicked (active) for each language with a true value in the collection. Whenever a different language is selected by clicking on its respect ...

Confirm the input validity using jQuery for radio buttons, checkboxes, and dropdown menus

When it comes to validating input fields like text, email, radio, checkbox, and select, I have the following structure in my form: <fieldset> <div class="form-top"> <div class="form-bottom"> <div class="for ...

The addScript feature seems to be experiencing difficulties upon the initial website load

Currently, I am utilizing the jquery.flexslider plugin and it is performing well. However, I have a specific requirement where I do not want to load the plugin for screens that are smaller than 600px. After experimenting with various scripts, I have final ...

Passing dynamic scope from Angular to a directive is a seamless process

I am working with a directive that retrieves an attribute value from an http call in the following manner: Controller app.controller("HomeController", function($scope){ $http.get("/api/source").then(function(res){ $scope.info = res.data }); }); ...

"Stellar.js fails to function properly when applied to elements loaded dynamically through AJAX requests

I recently implemented the amazing Stellar.js for parallax effects in a project of mine. However, I've encountered an issue: Stellar.js does not recognize when I update content via AJAX (specifically loading new div elements from an HTML file and rep ...

Creating a tree structure from an array in JavaScript, including the parent id enclosed in brackets

Before dismissing this question as a duplicate, please listen to me. I am working with a json response in reactjs that looks like the following organisationUnits: [ { name: "0.Mzondo", id: "nW4j6JDVFGn", parent: { ...

Vue component fails to trigger upon receiving the 'mouseleave' event

I am currently working on a navbar with dynamic component navigation, where hovering over a navbar-link should display the corresponding component and hiding it when the mouse leaves. Although the components are displayed correctly upon hover, they do not ...

Sending a collection of text inputs from a web form and saving them in MongoDB

I have been attempting to store an array of strings from my HTML form into my database (MongoDB). Here's the HTML form for creating a new class: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"& ...

Creating a new JSON by extracting a specific branch or node from an existing JSON data

I have a Nuki Smartlock and when I make two API calls to the Nuki Bridge, I receive JSON responses. I want to apply the same logic to both responses: When requesting for current states, the JSON looks like this: [{ "deviceType": 0, "nuk ...

Executing Java output to Node.js console using child_process execSync without buffering

Having an issue with the execSync call below: const { execSync } = require('child_process'); ... console.log('Checking Java version') let java_version= execSync('java -version').toString(); console.log('Java version:&apo ...

Is it possible in Typescript to assign a type to a variable using a constant declaration?

My desired outcome (This does not conform to TS rules) : const type1 = "number"; let myVariable1 : typeof<type1> = 12; let type2 = "string" as const; let myVariable2 : typeof<type2> = "foo"; Is it possible to impl ...

The steps to triggering a button click after e.preventDefault()

When attempting to prevent a click() event of a button by using preventDefault() after unbinding the button with unbind(), I encountered an issue where it did not work as expected. <script> $("#update2FAButton").on("click",function(e){ e.pre ...

What are some strategies for creating a recursive function in JavaScript that avoids exceeding the maximum call stack size error?

I need assistance creating a walking robot function in JavaScript, but I am encountering a call stack size error. function walk(meter) { if(meter < 0) { count = 0; } else if(meter <= 2) { count = meter; ...

What is the best way to incorporate multiple conditions within a React component?

When working in React, I have the ability to conditionally render any div using the following code snippet: {hasContent && <span>{value}</span> } Recently, I attempted to include two conditions as follows: {hasContent || hasDesc &am ...

Using Node.js and JWT: A guide to securely storing and using access tokens in the Authorization header

Has anyone encountered this issue before? I've searched extensively online but haven't found much information on the topic. I'm relatively new to using node and JWTs, and my goal is to generate a JWT and store it in the Authorization header ...

Combine two queries in JavaScript by using arrays

I have a unique challenge where I can only post once every 90 minutes, so here's my double question. First up, I need to create a function that can replace a specific character in a string with a space. //====================== EXAMPLE ============= ...

Exploring the capabilities of using Next.js with grpc-node

I am currently utilizing gRPC in my project, but I am encountering an issue when trying to initialize the service within a Next.js application. Objective: I aim to create the client service once in the application and utilize it in getServerSideProps (wit ...

Checkbox click event not triggering properly

I am facing challenges in triggering an onclick event for the "Elevation" checkboxes located at the URL provided above. <input type="checkbox" value="A" id="elevation_A" onclick="changeElevation(this.value);" /> For some reason, the "changeElevati ...

The functionality of Bootstrap tooltips becomes disabled as soon as any element on the page is clicked

When initializing Bootstrap tooltips on my page, I follow this approach <script> $(document).ready(function () { $(function () { $('[data-toggle="tooltip"]').tooltip(); }); }); </script> A questio ...

What is the reason for the jQuery plugin not being applied after replacing the page content with an Ajax response?

At the moment, I am utilizing jQuery ajax to dynamically add content to my website. Additionally, I have incorporated the jquery.selectbox-0.6.1.js plugin to enhance the style of select boxes on the page. The plugin successfully styles the select boxes up ...