Tips for adding a time increment of 24 hours to a date variable in Angular 6

My goal is to update a date variable called EndDate stored in localStorage by adding exactly 24 hours to it. The current value in the localStorage is Sun Jun 09 2019 20:39:44 GMT+0530 (India Standard Time).

    var endDate = new Date();
    endDate.setDate(new Date(localStorage.getItem("requestDate")).getDate() + 1);

When I tried running this code, the result was Mon Jun 10 2019 07:58:50 GMT+0530 (India Standard Time), which is incorrect due to the current datetime being added.

    var endDate = new Date();
    endDate.setDate(new Date(localStorage.getItem("requestDate")).getDate() + 1);
    // Perform necessary operations
    endDate.setTime(new Date(localStorage.getItem("requestDate")).getTime() + 24);

Upon trying the above code, the output reverted back to Sun Jun 09 2019 20:39:44 GMT+0530 (India Standard Time) as setTime overwrote the previous date value.

The Desired Output should be Mon Jun 10 2019 20:39:44 GMT+0530 (India Standard Time)

Answer №1

Give this a try, hopefully it will be successful

let expirationDate = new Date(localStorage.getItem("createdAt"));
expirationDate.setDate(expirationDate.getDate() + 1);

Answer №2

Instead of initializing a fresh Date object, consider creating one based on the data stored in your localStorage and then incrementing from there. To illustrate, take a look at the following code snippet:

var initialDate = new Date(localStorage.getItem("requestDate"));
var finalDate = new Date(initialDate);
finalDate.setDate(finalDate.getDate() + 1);
console.log('initial date', initialDate.toString());
console.log('final date', finalDate.toString());

I hope this explanation proves to be helpful :)

Answer №3

In order to add a certain number of days to a specific date, you can utilize the code snippet provided below.

const startingDate = new Date(localStorage.getItem("requestDate"));
const endingDate = new Date(startingDate);
endingDate.setDate(startingDate.getDate() + 1);

console.log("Starting date: " + startingDate);
console.log("Ending date: " + endingDate);

If you require adding hours to a specific date, you can use the following code snippet.

const hoursToAdd = 10;
const initialTime = new Date(localStorage.getItem("requestDate"));
const finalTime = new Date(initialTime.getTime() + (hoursToAdd * 60 * 60 * 1000));
console.log("Initial time: " + initialTime);
console.log("Final time: " + finalTime);

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

Unusual behavior exhibited by ng-if within a widget

Hey there, seeking some assistance here. I'm currently making edits to a widget and within the client HTML code, I've come across two ng-if statements (the first one was already there, I added the second). <li> <a ng-if="data.closed ...

AngularJS2 brings a powerful and seamless implementation of indexedDB for efficient

I'm on the hunt for an indexeddb implementation that works seamlessly with Angularjs2. While I stumbled upon this api at https://github.com/gilf/angular2-indexeddb, it appears to be lacking in active development and may not be ready for production use ...

Manage scss styles consistently across Angular projects with this Angular library designed to

In an effort to streamline my development process, I am looking to consolidate my commonly used styles that are defined in my Angular library. My goal is to easily leverage mixins, functions, variables, and more from my library in future projects. Previou ...

Execution issue with Typescript function

In my Nativescript project, I have the following TypeScript file: import { Observable } from 'tns-core-modules/data/observable'; import { isIOS } from "tns-core-modules/platform"; import { Color } from "tns-core-modules/color"; import { request, ...

When ng-test is executed in an Angular service, the function array.some is not found

After retrieving allUsers from the cache and initializing it, I then set the boolean value of specialUserExists based on a condition in allUsers using allUsers.some() (reference to the Array.prototype.some() method). service.ts @Injectable({ providedIn: ...

Ways to obtain the component reference when clicking in Angular 2?

<!--snippet from template file--> <custom-element ... other attributes (click)="handleClick()" </custom-element> @Component({ //selector and templateUrl }) class MainComponent{ handleClick(){ // Obtaining the re ...

"Exploring the process of unsubscribing or disposing of an interval observable based on a certain condition in Angular2 or

I am embarking on the journey into Rx and reactive programming, facing a situation that requires me to continuously monitor a hardware's status by sending a POST request to its REST API every 500ms. The goal is to stop the interval observable once the ...

Obtain form data as an object in Vue when passed in as a slot

Currently, I am working on developing a wizard tool that allows users to create their own wizards in the following format: <wiz> <form> <page> <label /> <input /> </page> <page> <label /> ...

The reason behind the ghost problem - classRef isn't recognized as a constructor

Recently, I encountered an issue where the app was not loading in the browser while running an Angular NX project locally with the command "start-dev": "nx run-many --target=serve --all". The screen would get stuck on our loading animat ...

Interference with ElementClickInterceptedException in Selenium is caused by the presence of a WebPack iframe within an Angular application, despite implementing WebDriverWait

Everything was going smoothly with my automation code until suddenly, an ElementClickIntercepted exception started occurring when trying to click the "Sign In" button on the login screen: public class LoginPage { private readonly IWebDriver driver; ...

Issue: The JSX element 'X' is missing any constructors or call signatures

While working on rendering data using a context provider, I encountered an error message stating "JSX Element type Context does not have any constructor or call signatures." This is the code in my App.tsx file import { Context } from './interfaces/c ...

Troubleshooting NativeScript 5: Uncovering the iOS Memory Woes of Crashes and Le

Check out this link for more information: https://github.com/NativeScript/NativeScript/issues/6607 Software Stack: NativeScript 5 Angular 7 Demo repository: https://github.com/reposooo/ns-out-of-memory This issue is based on a similar problem i ...

Error Message: Angular NullInjectorException - The provider for "[Object]" is not found

While developing a simple Flashcard application that performs CRUD operations using Angular, Node.js, Express, and PostgreSQL, I encountered the following error: flashcards-area.component.ts:24 ERROR NullInjectorError: R3InjectorError(AppModule)[Flashcard ...

Implement CSS to globally style material.angular's mat-card by customizing the background color

Looking for a way to globally change the background of mat-card on material.angular.io. I attempted adding the following code snippet to styles.css with no success. mat-card { background-color: purple; } ...

Angular directive to delete the last character when a change is made via ngModel

I have 2 input fields where I enter a value and concatenate them into a new one. Here is the HTML code: <div class="form-group"> <label>{{l("FirstName")}}</label> <input #firstNameInput="ngMode ...

Angula 5 presents a glitch in its functionality where the on click events fail

I have successfully replicated a screenshot in HTML/CSS. You can view the screenshot here: https://i.stack.imgur.com/9ay9W.jpg To demonstrate the functionality of the screenshot, I created a fiddle. In this fiddle, clicking on the "items waiting" text wil ...

What is the best approach to implementing role-based authentication within a MEAN application?

Currently, I am developing a mean stack application and looking to implement role-based authentication. For instance, if the user is an admin, they should have additional permissions and access rights. Any guidance on implementing this feature would be g ...

Avoiding Maximum Call Stack Size Exceeded in Observables: Tips and Tricks

After filtering, I have a list stored in the variable filteredEvents$: public filteredEvents$ = new BehaviorSubject([]); I also have a method that toggles the checked_export property and updates the list: public checkAll(): void { this.filteredEve ...

Encountering an error in Angular 8 with the plugin: Unhandled ReferenceError for SystemJS

I recently followed a tutorial on integrating plugins into my Angular application at this link. I'm trying to create a component in my Angular app that can execute and display an external component. However, I encountered the following error: Uncaugh ...

Error: The JSON file cannot be located by the @rollup/plugin-typescript plugin

I have recently set up a Svelte project and decided to leverage JSON files for the Svelte i18n package. However, I am facing challenges when trying to import a JSON file. Although the necessary package is installed, I can't figure out why the Typescri ...