Adding 30 Days to a Date in Typescript

Discovering Typescript for the first time, I'm attempting to calculate a date that is (X) months or days from now and format it as newDate below...

When trying to add one month:

const dateObj = new Date();
const month = dateObj.getUTCMonth() + 2;
const day = dateObj.getUTCDate();
const year = dateObj.getUTCFullYear();

const newDate = `${month}/${day}/${year}`;

The result shows:

13/6/2022

Attempting to add 30 days instead:

const dateObj = new Date();
const month = dateObj.getUTCMonth() + 1;
const day = dateObj.getUTCDate() + 30;
const year = dateObj.getUTCFullYear();

const newDate = `${month}/${day}/${year}`;

This results in:

12/36/2022

The example not only provides incorrect month & day values but also fails to advance the year.

Any suggestions?

Answer №1

By utilizing the setDate() and getDate() functions, you can manipulate the value of dateObj without relying on Moment or any other external library:

// illustrating automatic handling of year/month change with a hard-coded date
var dateObj = new Date('2022-12-06');

// adding 30 days
dateObj.setDate(dateObj.getDate() + 30); // Results in 2023-01-05

var month = dateObj.getUTCMonth() + 1;
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();

var newDate = month + "/" + day + "/" + year;

console.log(newDate)

Observe how the code automatically manages the changes in month and year for you.

Answer №2

To update the date, use the setDate() method.

var futureDate = new Date();
futureDate.setDate(futureDate.getDate() + X_DAYS);

Answer №3

The solution demonstrated in this answer showcases the functionality of the Date object when handling invalid values such as exceeding range limits for specific components like the day of the month. The Date object wraps the number and intelligently manages overflow by applying it algorithmically to the next component, such as the month.

For instance, trying to add 30 to 6 would result in 36 as the new day of the month, which is not a valid value within the JavaScript Date object's limit.

If you prefer not to depend on this behavior, maybe because you need a generic solution that can be applied to other programming languages or date frameworks that do not handle overflow automatically, you can manually tweak the numeric representation using some conversion mathematics techniques:

TS Playground

const date = new Date(Date.UTC(2022, 11, 6));
console.log(date.toISOString()); // 2022-12-06T00:00:00.000Z

const dayInMs = 1000 * 60 * 60 * 24;

date.setTime(date.getTime() + (30 * dayInMs));

console.log(date.toISOString()); // 2023-01-05T00:00:00.000Z

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

The specified type '{ data: any; }' is incompatible with the type 'IntrinsicAttributes'. The property 'data' is not found in the type 'IntrinsicAttributes'

I'm encountering issues with the data property. interface Props { params: { slug: string }; } const Page = async ({ params }: Props) => { const data: any = await getPage(params.slug); // This section dynamically renders the appropriate orga ...

When using setInterval, the image remains static on Safari but updates on Chrome

In my project, I am using a mock array to distribute data. One part of the project utilizes this data to display a list of cases, each with assigned images. When a case is hovered over, the images associated with that case are displayed one at a time, with ...

Can a substring within a string be customized by changing its color or converting it into a different HTML tag when it is defined as a string property?

Let's discuss a scenario where we have a React component that takes a string as a prop: interface MyProps { myInput: string; } export function MyComponent({ myInput }: MyProps) { ... return ( <div> {myInput} </div> ...

What is the best way to fill the dropdown options in every row of a data table?

This HTML snippet displays a data table with test data and corresponding dropdown options. <tr> <th> Test Data </th> <th> Test Data ...

Bidirectional communication linking an Angular 2 component and service utilizing the power of Observables

I'm having difficulties establishing a simple connection between an Angular 2 component and service using Observable. I've been trying to achieve this, but I can't seem to get it right. Here's the scenario: My component HeroViewerCompo ...

Checking for Object Equality in TypeScript

I'm working on a TypeScript vector library and encountered my first failed test. The issue revolves around object equality in TypeScript/JavaScript, and despite searching through TypeScript's official documentation (http://www.typescriptlang.org ...

Encountered difficulties when trying to incorporate SCSS into my rollup build

Desired Outcome I aim to develop a small library for personal use, focusing on separating code into library (product) and application (project) code. All my source code resides in the /src folder, consisting of React, TypeScript, and SCSS code. I would l ...

The S3 signature verification failed while generating a signed URL on the server-side using Node.js

Trying to upload a video file to my bucket using a pre-signed URL in angular4. Instructions: let s3 = new AWS.S3(); s3.config.update({ accessKeyId: process.env.VIDEO_ACCESS_KEY, secretAccessKey: process.env.VIDEO_SECRET_KEY }) ...

Discovering the object and its parent within a series of nested arrays

Is there a way to locate an object and its parent object within a nested array of unknown size using either lodash or native JavaScript? The structure of the array could resemble something like this: name: 'Submodule122'</p> I have been ...

Encountered an issue during the Jest test where the error message states 'Cannot call Class constructor Stack without using the keyword 'new''

I have encountered an issue with my Jest test for an AWS CDK configuration import { expect as expectCDK, matchTemplate, MatchStyle } from '@aws-cdk/assert'; import * as cdk from '@aws-cdk/core'; import { KmsMultiregionPrincipalKey } fro ...

Syntax for TypeScript generic promises definition

I'm struggling to fully grasp the definition of Promise in TypeScript, as shown below: /** * Represents the completion of an asynchronous operation */ interface Promise<T> { /** * Attaches callbacks for the resolution and/or rejectio ...

Swap out a collection of objects for a different collection of objects

I need to replace the content of array1 with the content of another array2 while keeping the same references and indexes in array1: let array1 = [ { book : { id : 2, authorId : 3} } , { book : { id : 3, authorId : 3} }, { book : { id : 4, authorId : ...

How to upload files from various input fields using Angular 7

Currently, I am working with Angular 7 and typescript and have a question regarding file uploads from multiple input fields in HTML. Here is an example of what I am trying to achieve: <input type="file" (change)="handleFileInput($event.target.files)"&g ...

Tips for preserving updates following modifications in Angular 5/6?

I'm currently working on enhancing the account information page by implementing a feature that allows users to edit and save their details, such as their name. However, I am encountering an issue where the old name persists after making changes. Below ...

What is the most efficient way to remove all typed characters from fields when clicking on a different radio button? The majority of my fields share the same ngModel on a separate page

Is there a way to automatically clear all typed characters in form fields when switching between radio buttons with the same ngModel on different pages? I noticed that the characters I type in one field are retained when I switch to another radio button. ...

An Unexpected ER_BAD_FIELD_ERROR in Loopback 4

I encountered an unusual error: Unhandled error in GET /managers: 500 Error: ER_BAD_FIELD_ERROR: Unknown column 'role_id' in 'field list' at Query.Sequence._packetToError (/Users/xxxx/node_modules/mysql/lib/protocol/se ...

Angular 2 GET request returns a 404 error

I have been attempting to reproduce the ngPrime datatable demo from this Github repository. Currently, I am working with the most recent version of Angular (4) and using angular-cli in development mode. Placing a JSON file into my app folder where the serv ...

Managing Angular routing: selectively updating named outlets without reloading submodules

My routing configuration currently reloads Module2 ListComponent on every routing event. However, I want to prevent the list from reloading when a user clicks on a list item within ListComponent. Specifically, when navigating from module2/route1 to module ...

Unable to update markers on agm-map for dynamic display

In my Angular 5 application, I am utilizing Angular Google Maps (https://angular-maps.com/) along with socket.io for real-time data updates of latitude and longitude from the server. Although I am successfully pushing the updated data to an array in the co ...

React Native Material - Implementing a loading indicator upon button press

With React Native Material, I am trying to implement a loading feature when a button is clicked. The goal is to show the "loading" message only when the button is active, and hide it otherwise. Additionally, I would like for the loading message to disappea ...