calculate the difference between two dates and then add this difference to a new date

Utilizing TypeScript for date calculations.

Example:
Initial Date 1: "10/06/2021 10:10:05"
Initial Date 2: "08/06/2021 11:10:05"

Calculate the difference between the two dates, including date/month/year/hour/min/sec/milliseconds. Ensure compatibility with all time regions.

Calculated Difference:
2 days = 10/06/2021 10:10:05 - 08/06/2021 11:10:05

Updated Date 1:
Add the calculated difference to Date 1.
New Date 1 = 12/06/2021 HH:MM:SS

Answer №1

To find the difference between two dates, consider that it could be negative depending on the order of the dates provided. If you want to subtract the earlier date from the later one, simply remove the Math.abs function in the code snippet below. Everything else will function as expected.

var date1: Date = new Date("10/06/2021 10:10:05")
var date2: Date = new Date("08/06/2021 11:10:05")

var dateDifference = Math.abs(date1.valueOf() - date2.valueOf());

var newDate = new Date(date1.valueOf() + dateDifference);

console.log(newDate)

The above code will result in 2021-12-06T03:40:05.000Z. If you prefer the format 06/12/2021 9:10:05, use the following snippet:

console.log(newDate.toLocaleDateString('en-GB', { month: '2-digit',day: '2-digit',year: 'numeric'}) + " " + newDate.toLocaleTimeString().substring(0, 7))

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

Trouble arises when managing click events within the Material UI Menu component

I've implemented the Menu Component from Material UI as shown below - <Menu open={open} id={id} onClose={handleClose} onClick={handleClick} anchorEl={anchorEl} transformOrigin={{ horizontal: transformOriginRight, vertical: t ...

A universal TypeScript type for functions that return other functions, where the ReturnType is based on the returned function's ReturnType

Greetings to all TypeScript-3-Gurus out there! I am in need of assistance in defining a generic type GuruMagic<T> that functions as follows: T represents a function that returns another function, such as this example: fetchUser(id: Id) => (disp ...

Is there a way to restrict the return type of a function property depending on the boolean value of another property?

I'm interested in creating a structure similar to IA<T> as shown below: interface IA<T> { f: () => T | number; x: boolean } However, I want f to return a number when x is true, and a T when x is false. Is this feasible? My attempt ...

What is the best way to send two separate properties to the selector function?

My selector relies on another one, requiring the userId to function properly. Now, I want to enhance the selector to also accept a property named "userFriend". However, there seems to be an issue with passing this new parameter, as it only recognizes the ...

Trouble with 'import type' declaration causing build issues in a Next.js project

Having trouble importing the Metadata type from the next module. The code snippet below is directly from the Next.js documentation. THE ISSUE client.js:1 ./app/layout.tsx:3:12 Syntax error: Unexpected token, expected "from" 1 | import React from 'r ...

The ngOnChanges lifecycle hook does not trigger when the same value is updated repeatedly

Within my appComponent.ts file, I have a property called: this._userMessage Afterwards, I pass it to the childComponent like so: <child-component [p_sUserMessage]='_userMessage'></child-component> In the childComponent.ts file: @ ...

Ensuring Commitments in the ForEach Cycle (Typescript 2)

Having trouble with promise chains after uploading images to the server in Angular 2 and Typescript. Let's come up with some pseudo-code: uploadImages(images):Promise<any> { return new Promise((resolve, reject) => { for (let imag ...

Having trouble declaring a module in an npm package with Typescript?

I'm currently working on a project using Vue.js and TypeScript. Within project "A," I am utilizing a private npm package called "B," which serves as a component library. This package "B" also incorporates another library, 'tiptap,' which unf ...

Is it advisable to send a response in Express.js or not?

When working with Express.js 4.x, I'm unsure whether to return the response (or next function) or not. So, which is preferred: Option A: app.get('/url', (req, res) => { res.send(200, { message: 'ok' }); }); Or Option B: ...

Steps to develop a collaborative NPM package

I am currently in the process of developing an NPM package using Typescript that contains solely my type interfaces. At the moment, my project has the following folder structure: project │ index.ts │ └───types │ restaurant.ts │ ...

Error in NextJS with TypeScript when updating data in a useState variable

Recently, I started working with TypeScript, ReactJS, and NextJS, but I encountered a TypeScript error that I need help fixing. My current project involves using NextJS 14, server actions, and Prisma as the ORM for a university-related project. An issue ar ...

Typescript constructor that accepts an object as an argument instead of traditional parameters

My constructor is becoming lengthy and not structured the way I would prefer. I am looking to pass an object to my constructor so that I can access fields by their names. Here is how the class looks currently. export class Group { id: string; constru ...

Tips for managing Razorpay responses in Angular 2

I'm currently in the process of finalizing my payment transaction through RazorPay Payment gateway, and I've attempted to do so as shown below: var options = { "key": "XXX", "amount": 100, "name": "Ezshipp", "description": this.it ...

Unable to transfer an object into a component due to a subscribe restriction

I have encountered an issue: I am making a post request to save an object in the database. The request takes JSON input with the values of the object to be saved. After saving the object in the database, I need my servlet to return the saved object so that ...

Ensuring TypeScript's strict null check on a field within an object that is part of an

When using TypeScript and checking for null on a nullable field inside an object array (where strictNullCheck is set to true), the compiler may still raise an error saying that 'Object is possibly undefined'. Here's an example: interface IA ...

Troubleshooting issues with importing modules in TypeScript when implementing Redux reducers

Struggling to incorporate Redux with TypeScript and persist state data in local storage. My current code isn't saving the state properly, and as I am still new to TypeScript, I could really use some suggestions from experienced developers. Reducers i ...

What is the best way to resolve the unusual resolution issue that arises when switching from Next.js 12 to 13

Previously, I created a website using nextjs 12 and now I am looking to rebuild it entirely with nextjs 13. During the upgrade process, I encountered some strange issues. For example, the index page functions properly on my local build but not on Vercel. ...

You are unable to compile a module in Visual Studio Code unless you provide the --module flag

I am facing an issue with my TypeScript code file that appears to be a common error, but I'm struggling to resolve it. This problem is new to me as I am still getting acquainted with Visual Studio Code. Cannot compile modules unless the '--modul ...

Converting an array of arrays into an object with an index signature: A step-by-step guide

I find myself facing a challenge where I have two types, B and A, along with an array called "a". My objective is to convert this array into type B. Type A = Array<[string, number, string]>; Type B = { [name: string]: { name: ...

Is there a way to conceal 'private' methods using JSDoc TypeScript declarations?

If we consider a scenario where there is a JavaScript class /** * @element my-element */ export class MyElement extends HTMLElement { publicMethod() {} /** @private */ privateMethod() {} } customElements.define('my-element', MyElement) ...