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

Creating a TypeScript schema with nested maps and arrays using Dynamoose

I'm currently in the process of developing a schema for a specific example: { "foods": [ { "fruits": [{ "apple": { "color": "red", ...

Encountering intellisense problems while declaring or utilizing TypeScript types/interfaces within Vue.js Single File Component (SFC) documents

For my Nuxt 3 project, I am developing a component and attempting to declare an interface for the component props to ensure strong typings. Here is an example: <script setup> interface Props { float: number; } const props = defineProps<Props> ...

What is the most effective method to query Prisma using a slug without utilizing a React hook?

Retrieve post by ID (slug) from Prisma using getStaticProps() before page generation The challenge arises when attempting to utilize a React hook within getStaticProps. Initially, the plan was to obtain slug names with useRouter and then query for a post ...

NestJS is having trouble importing generated types from the Prisma client

When working with Prisma in conjunction with NestJs, I encountered an issue after defining my model and generating it using npx prisma generate. Upon importing the generated type, I can easily infer its structure: import { FulfilmentReport, FulfilmentRepor ...

Understanding the timing of records being returned via an Observable in Angular's ngOnInit

In my Angular 2 application, I am using an observable to keep track of an array of records. As the results of this observable are stored in the variable "records", I am utilizing *ngFor="let record of records" to iterate over and display them in my view. ...

Tips on optimizing data processing for quicker display with ngFor

I am currently facing an issue with loading a JSON file containing 3500 data. The data appears very slowly on the view, causing the application to work sluggishly. Below is a snippet of the JSON: export class Service { private items = new Arr ...

The extend keyword in TypeScript causing issues with type inference

Why is TypeScript showing an error in the code below? type A = { kind: "a" } type B = { kind: "b" } const a = (a: A): void => undefined const b = (b: B): void => undefined const c = <C extends A | B>(c: C): void => (c.kind == "a" ? a(c) : ...

Angular 2 Mixup: Using Leaflet and Google Maps with Incorrect Tile Order

I am encountering an issue while working on Leaflet and Google within Angular 2. The problem lies in the Tilemill tiles not rendering properly as they are displaying in a strange order. Here is a screenshot of the current state: https://i.stack.imgur.com/ ...

eliminate any redundant use of generics

Recently, I attempted to create a pull request on GitHub by adding generics to a method call. This method passes the generically typed data to an interface that determines the return type of its methods. However, the linter started flagging an issue: ERR ...

Having trouble utilizing HTML Canvas in the newest release of Angular and TypeScript

After extensive searching on the internet, I have not been able to find any working examples of using HTML canvas in Angular. It seems that changes in syntax in Typescript and Angular's newer versions have rendered all existing solutions obsolete. I ...

The element class type 'xxx' is lacking several properties compared to the 'ElementClass' type, including context, setState, forceUpdate, props, and others. This issue is flagged with error code TS2605

Encountering an error while attempting to execute my react app: D:/React/my-components/src/App.tsx TypeScript error in D:/React/my-components/src/App.tsx(23,4): JSX element type 'Confirm' is not a constructor function for JSX elements. ...

Rotate object within HTML table

I have a simple data structure as shown below: [ { "ClientId": 512, "ProductId": 7779, "Date": "2019-01-01", "Quantity": 20.5, "Value": 10.5 }, { "ClientId": 512, "ProductId": ...

After logging out, Next-auth redirects me straight back to the dashboard

In my NextJS application, I've implemented a credential-based authentication flow along with a dashboard page. To handle cases where an unauthorized user lands on the dashboard route, I've created a custom AccessDenied component. In the getServer ...

When working with TypeScript, it's important to note that an implicit 'any' type may occur when trying to use an expression of type 'string' to index a specific type

Currently, I'm attempting to transfer a custom hook used in Vue for handling i18n from JavaScript to TypeScript. However, I am encountering a persistent error message: An element is implicitly assigned the type 'any' due to an expression o ...

The deletion of property '1' from the [object Array] is not possible

How to Retrieve a List in My Components Using Input : @Input() usersInput: Section[]; export interface Section { displayName: string; userId: number; title: number; } Here is the Value List : 0: displayName: "بدون نام" ...

In React + TypeScript, learn how to effectively pass down a function from a container component to a

I am currently working on developing a tabs application using React and Typescript. The main component, Tabs, manages the state and passes it down to the Content component. Additionally, I have implemented a function called 'handleName' which is ...

Can you use the useCallback function within a nested callback function?

within component A: const retrieveOnClick = useCallback( (rec: GenericRec): (() => void) => () => { setSelectedRecord(rec); }, [], ); inside component B which is a child of A: const displayRecord = useCallback( (row: Row& ...

Failure in Dependency Injection in Angular with Typescript

My mobile application utilizes AngularJS for its structure and functionality. Below is the code snippet: /// <reference path="../Scripts/angular.d.ts" /> /// <reference path="testCtrl.ts" /> /// <reference path="testSvc.ts" /> angular.mo ...

Tips for preventing the ngbTypeahead input field from automatically opening when focused until all data is fully mapped

When clicking on the input field, I want the typeahead feature to display the first 5 results. I have created a solution based on the ngbTypeahead documentation. app.component.html <div class="form-group g-0 mb-3"> <input id="typ ...

Ways to cancel a subscription once a specific parameter or value is met following a service/store interaction

I am working with a service that provides a changing object over time. I need to unsubscribe from this service once the object contains a specific property or later when the property reaches a certain value. In situations like these, I typically rely on t ...