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

Encountering an issue with d3 Angular 2 pie chart related to d3.arc data

I encountered a problem with my code: 'PieArcDatum' is not assignable to parameter of type 'DefaultArcObject.' at this specific line Argument of type return "translate(" + labelArc.centroid(d) + ")";. Could someone please assist me in ...

Elevated UI Kit including a setFloating function paired with a specialized component that can accept

I am currently experimenting with using Floating UI alongside various custom React components. These custom components create internal element references for tasks like focus and measurements, but they also have the capability to accept and utilize a RefOb ...

Tips for retrieving a server-set cookie in your Angular 2 application, and guidelines for including the same cookie in requests made by your Angular 2 application

Requirement: Our application should be able to support the same user opening our web application as a separate session. The issue is not about how to use cookies in Angular 2, but rather how the server can retrieve cookies from the HTTPServletRequest obje ...

Creating definitions for generic static members within a third-party module

There is a 3rd party module with the following structure: export class Container{ static async action() { return {...} } constructor(params = {}) { // ... } async doSomething(params = {}) { // ... } } I am looking to de ...

Ways to establish the relationship between two fields within an object

These are the definitions for two basic types: type AudioData = { rate: number; codec: string; duration: number; }; type VideoData = { width: number; height: number; codec: string; duration: number; }; Next, I need to create a MediaInfo typ ...

When a 404 error is thrown in the route handlers of a Next.js app, it fails to display the corresponding 404 page

I am encountering an issue with my route handler in Next.js: export async function GET(_: Request, { params: { statusId } }: Params) { const tweetResponse = await queryClient< Tweet & Pick<User, "name" | "userImage" | &q ...

There is no 'next' property available

export function handleFiles(){ let files = retrieveFiles(); files.next(); } export function* retrieveFiles(){ for(var i=0;i<10;i++){ yield i; } } while experimenting with generators in T ...

The TypeScript compilation is not able to find index.ts at the moment

When I tried to run 'ng serve', I encountered the following error message: The TypeScript compilation is missing node_modules/angular2-indexeddb/index.ts. It is crucial to ensure that this file is included in your tsconfig under the 'file ...

Understanding authorization and user roles within an Angular 2 application utilizing Microsoft Graph

As a newcomer, I am in the process of developing a CVThèque application using angular 2 and .net core. For authentication purposes, I have integrated Microsoft Graph and adal successfully. However, I am unsure how to set up permissions and group roles for ...

Can a dynamic HTML page be created using Angular's ngClass directive and Bootstrap classes to ensure responsiveness?

Is there a way to dynamically resize buttons in my Angular application using the Bootstrap class btn-sm? I'm currently using this code snippet: <button [ngClass]="{ 'btn-sm' : window.screen.width < '575.5px' }"> ...

Typescript is throwing an error when trying to use MUI-base componentType props within a custom component that is nested within another component

I need help customizing the InputUnstyled component from MUI-base. Everything works fine during runtime, but I am encountering a Typescript error when trying to access the maxLength attribute within componentProps for my custom input created with InputUnst ...

Struggling to find a solution for your operating system issue?

We are currently attempting to utilize the markdown-yaml-metadata-parser package for our project. You can find more information about the package here. Within the package, it imports 'os' using the following syntax: const os = require('os ...

What is causing the error 'router-outlet' to be unrecognized in Angular version 17?

I have recently set up a new angular project using Angular 17: If 'router-outlet' is considered an Angular component, double check that it is part of this module. If 'router-outlet' is recognized as a Web Component, make sure to inclu ...

Production is experiencing a hiccup, however, the site is still up and running. There seems to be

Having an error in production that I can't seem to replicate on my local machine. The error message reads: src/controllers/userController.ts(2,29): error TS2307: Cannot find module '../services/UserService' or its corresponding type declarat ...

CdkVirtualFor does not display any content

I'm facing an issue with implementing cdk-virtual-scroll in my chat application. Unfortunately, it's not showing anything on the screen. Strangely, when I resort to using the regular "ngFor", everything works smoothly. However, as soon as I switc ...

Error: An unauthorized attempt was made to modify property settings for certain users, which are designated as read-only

Within my Ionic app, there exists a specific page where users have the ability to modify information related to a particular city. What I aim to achieve is for these modifications to only be visible to other users who are also located within the same "City ...

Angular 5 ngIfElse: How to save the outcome of a condition in a storage container

Code Snippet: <mat-icon [ngClass]='{ rotate: !users }'>refresh</mat-icon> <div *ngIf="usersObservable | async as users; else loading"> ... </div> <ng-template #loading let-users> Waiting... </ng-template> ...

Tips for adding Google Tag Manager to a popup within a Chrome extension?

I have successfully developed a chrome extension. In the popup HTML, I added the Google Tag Manager script and a noscript iframe like this: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Signals< ...

Retain the parameter name when defining a function type mapping

Imagine you need to change the result of a function: (bob: Bob) => R => (bob: Bob) => R2 Is it possible to achieve this without changing the argument name? (e.g bob instead of using a general name like a) ...

Using Angular DataTables to make an AJAX call from browser's local storage

I am exploring a method to retrieve data from local storage via an ajax call and load it into a table as a JSON object. fetchDataForTable() { this.jsonService.retrieveJson().subscribe(response => { this.dataToDisplay = response.data; }); t ...