Include a future date with a date extracted from a JSON response

I have retrieved a date from a JSON response. After confirming that the date is indeed a valid date type, I am having trouble setting it to a future date. The snippet of code below shows my attempt:

$rootScope.until = response.data.data.dateReceived;

//return future date
// var targetDate = new Date();
$rootScope.until.setDate($rootScope.until + 60); // adding 60 days but unable to do so

// Display the date we have created
$rootScope.until = $filter("date")($rootScope.until, 'EEEE, MMMM d, y');

Can someone please advise me on how to add future dates?

Answer №1

It appears that there are two errors in this situation.

  1. You are attempting to utilize Date functions on a Number data type.
  2. The function Date#setDate() requires the argument to be the day of a month, not the timestamp itself.

Date vs. Number

Issue

If you were to use new Date(response.data.data.dateReceived) to convert the milliseconds into a Date data type, you would have access to methods like setDate().

However, in your current code, you are trying to execute setDate() on what JavaScript perceives as just a regular number. To JavaScript, it may as well be -1, as it doesn't recognize any significance beyond its numeric value.

Resolution

Given that your input data is in milliseconds (as mentioned in the comments), a simple solution would be to add milliseconds to your original timestamp like this:

const SIXTY_DAYS = 5184e6; //1000ms/sec * 3600secs/hour * 24hours/day * 60days
$rootScope.until = response.data.data.dateReceived + SIXTY_DAYS;

Ensure that the value is a number and not a string to avoid concatenation instead of addition.


setDate arguments

Issue

If you do have a variable with a Date data type (as mentioned earlier), you would have access to methods like Date.setDate(). However, the arguments for this method differ from what your code assumes.

Resolution

setDate() requires a number representing days since the start of the month as its argument. To add a specific number of days, you can use the following code:

$rootScope.until = new Date(response.data.data.dateReceived);
$rootScope.until.setDate($rootScope.until.getDate() + 60);

This code will calculate the day of the month for the date, then add 60 days to that value, automatically adjusting for changes in the month.

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

Using a static string in Javascript yields no issues, whereas working with variables can sometimes cause problems

I've been struggling with a problem this morning and it's time to ask for help! I have a JavaScript function that takes the value entered by a user into an autocomplete box, uses AJAX to send that value to a PHP script which then queries the data ...

Navigating the implementation of undefined returned data in useQuery hook within Apollo and ReactJS

I am facing an issue with my code where the cookieData is rendered as undefined on the initial render and query, causing the query to fail authentication. Is there a way to ensure that the query waits for the response from the cookie API before running? co ...

Issue with interaction between jQuery AJAX and PHP login functionality

Currently, I am attempting to implement an inline login feature that triggers whenever the PHP $_SESSION['logged_in'] variable is not defined (this variable gets set when a user logs in). The challenge arises when I try to keep the user on the sa ...

Is there a way to dim and deactivate a button after it has been clicked once?

Hello, I am attempting to disable and grey out a button after it has been clicked once in order to prevent the user from clicking it again until they refresh the page. I hope my question is clear enough and that you can understand me. Below is the HTML cod ...

Discovering the clicking actions on PDF elements within an HTML environment

I am currently working on developing a web application that involves rendering various pdf objects. My main goal is to be able to detect the position of a click inside the pdf container. However, it seems like the OnClick event is not functioning as expe ...

Exploring the use of global variables in React

Welcome to my React learning journey! I've encountered an issue while trying to access a global variable exposed by a browser extension that I'm using. Initially, I attempted to check for the availability of the variable in the componentDidMount ...

Utilizing React and Material-UI to create an autocomplete feature for words within sentences that are not the first word

Looking to enable hashtag autocomplete on my webapp, where typing #h would display a menu with options like #hello, #hope, etc. Since I'm using material-ui extensively within the app, it would be convenient to utilize the autocomplete component for th ...

Inhibit the ASP:dropdownlist when the value of another ASP:Dropdownlist is selected

Trying to modify two asp.net dropdownlists using client-side JavaScript is my current challenge. Specifically, these dropdowns are located within a modal that opens with a function. The objective is to disable the second dropdown (dropdown2) whenever the ...

Obtain a transformed mesh that has been displaced using a displacementMap within three.js

Seeking to extract and export the mesh affected by a displacementMap. The displacement of vertexes is determined by this line in the shader (taken from three.js/src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl): transformed += normalize(obje ...

Behavior of routing not functioning as anticipated

In my app-routing.module.ts file, I have defined the following routes variable: const routes: Routes = [ { path: '', redirectTo: '/users', pathMatch: 'full' }, { path: 'users', component: UsersComponent }, ...

Issue with Angular: no action taken when re-calling function and utilizing the

In one of my components, I am using route parameters to switch between different "tabs". Whenever I switch tabs, I call a function specific to that tab which is subscribed to the route parameters. Here is an example of one of those functions: getUserFeed( ...

Slideshow elements removed

I attempted to remove my links individually from the div id="wrapper", but unfortunately have encountered an issue while doing so: window.onload = function () { setInterval(function () { var wrapper = document.getElementById("wrapper"); var my_l ...

Is there a way to postpone these animations without relying on setTimeout?

As I develop a single-page website, my goal is to smoothly transition between sections by first animating out the current content and then animating in the new content. Currently, I have achieved this using setTimeout(), where I animate out the current con ...

Several conditional statements in JSX

In my JSX Return() code, I am encountering an "If" issue when one of my conditions has 2 different 'onClick' events. There are 2 'a' tags, where one will display button 'X' if a statement is true and the other will display but ...

Sending data from a React application to a Node.js server using Axios

Hello, I am facing an issue with an axios request to post data to a Node.js server. When trying to access this data on the server, it is showing as undefined. Below is the function for posting data: function Submit() { let params={ firstName: ...

Tips for aggregating the values of object arrays in React props

I need help sorting three top-rated posts. Currently, the function displays three post titles along with their ratings, but they are not sorted by best rating. Can anyone assist me with this issue? {posts.slice(0, 3).sort((a, b) => ...

Managing Users in a Web App with AngularJS, Spring, and Hibernate

Thought-Provoking Inquiry Back-End Strategy In the process of developing the User Management Module for a Web application, I am working with three tables: User, Role, and UserInterce. The user table is connected to the role table in a ManyToMany relations ...

Is there a way to transform JSON into HTML with PHP?

I am attempting to reverse engineer the function referenced in this discussion: [Post][1] [1]: https://stackoverflow.com/a/23427469/19867306 @scozy demonstrated a function for converting HTML text to a JSON model. Now, I need to convert the same JSON mode ...

The commitment to Q ensures that errors and exceptions are effectively communicated

Here is a code snippet that I am using to transform a traditional nodejs function into a promise-based one: Object.defineProperty(Function.prototype, "toPromise", { enumerable: false, configurable: false, writable: false, value: function ...

Eliminate any line breaks from the information retrieved from the node event process.stdin.on("data") function

I've been struggling to find a solution to this issue. No matter what approach I take, I can't seem to remove the new line character at the end of my string. Take a look at my code below. I attempted using str.replace() in an effort to eliminate ...