A step-by-step guide on increasing native Time variables in JavaScript

How can I dynamically and repetitively add time (both hours and minutes) in JavaScript to effectively increment a date object? There are times when I need to add minutes, or hours, or a combination of both - and I want the resulting total time to be returned correctly as an incremented or decremented valid time/date object.

For example, when adding up the hours across table rows/grids, sometimes the duration being added is unknown beforehand. Some cells contain minutes, while others have HH:mm format. The answers on Stack Overflow do not address incrementing with dynamic times or handling date manipulations like moving the date forward or backward for negative deductions.

I've been manually performing these calculations and missing many scenarios.

var newDateObj = new Date(oldDateObj.getTime() + diff*60000);

How can I achieve this dynamically and have the newDateObj accurately auto-increment hours or days?

var newDateObj = oldDateObj + AddMinsTimeObj; // Adding minutes
var newDateObj = oldDateObj + AddHoursTimeObj; // Two hours
var newDateObj = oldDateObj + AddHoursMinsTimeObj; // 1 hour and 40 mins
var newDateObj = oldDateObj + AddDaysHoursMinsTimeObj; // Days, hours, and minutes

In other programming languages like Java and C#, you can simply add time, dates, and time spans using functions like

System.DateTime addDynamicTimeOrDuration = today.Add(duration);
, where the duration could be specified in various formats like "1hr:30" or "220 mins". How can we achieve the same functionality in JavaScript?


Update 1: Many suggestions point towards using moment.js for durations, but according to the documentation links provided, creating durations directly from datetime objects may not be supported.


Update 2:

I am attempting the following code snippet, getting closer to a solution

moment().add($this.val + moment().diff(date1, date1))
;


Essentially, I want a function that allows me to add time intervals together seamlessly and obtain correct results, regardless of whether the input specifies minutes, hours, or days. This should ideally be handled by a preexisting function in the base library, making it easier to manage complex date calculations in JavaScript.

Answer №1

When using Moment.js, it becomes possible to calculate the exact difference in milliseconds between two specified date objects.

const start = moment([1990, 4, 25]);
const end = moment([2021, 8, 15]);
const timeDifference = end.diff(start);

This will provide you with the precise number of milliseconds that exist between the two defined points in time. You don't have to worry about converting this into seconds, minutes, or hours for your calculations - Moment.js has got it covered.

const futureDate = moment().add(timeDifference, 'ms');

The output here will be a Moment object representing a date far into the future, equivalent to my current age added to the present moment.

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

Is there a way to bypass the default layout on app router in Next.js and implement our own custom page layout

Utilizing a default layout in layout.jsx, I passed all my other pages as children through props. In the page router, we typically configure the router path to specify which layout to use. However, in this new system, I am facing challenges with coding it. ...

Cross-Origin Resource Sharing (CORS): The preflight request response does not satisfy the access control check

I've been facing an issue with a simple POST method to my API through the browser. The request fails, but when I try the same on Postman, it works fine. The response includes a JSON string and two cookies. In an attempt to resolve this, I set the hea ...

The data is not being successfully transmitted to the controller method through the AJAX call

In my JavaScript file, I have the following code: $(document).ready(function () { $('#add-be-submit').click(function (event) { event.preventDefault(); $.ajax({ type: 'POST', url: '/snapdragon/blog/new&apos ...

Changing a background image url using jQuery by clicking a button

I'm struggling to find a way to use jQuery to add a background image URL to my CSS. Everything I've attempted so far has been unsuccessful. let button = document.querySelector('form button.btn') button.addEventListener('click&ap ...

Showing the Datepicker from jQuery right in the middle of the screen

Here's the generated code as default: <div id="ui-datepicker-div" class="ui-datepicker ui-widget ui-widget-content ui-helper- clearfix ui-corner-all ui-datepicker-multi ui-datepicker-multi-2" style="width: 34em; position: absolute; left: ...

What is the best approach for dynamically appending new elements to a JSON array using PHP?

I am facing an issue with the JSON below: [{"username":"User1","password":"Password"}, {"username":"User5","password":"passWord"},] The above JSON is generated using the PHP code snippet mentioned below: <?php $username = $_POST["username"]; ?>&l ...

Sending data using formData across multiple levels of a model in Angular

I have a model that I need to fill with data and send it to the server : export interface AddAlbumeModel { name: string; gener: string; signer: string; albumeProfile:any; albumPoster:any; tracks:TrackMode ...

Include a "remember me" feature in the Stripe form

I am currently working on an exciting project using Angular 6. Within my website, I have decided to integrate the Stripe payment system. However, I would like to incorporate a unique and default "remember me" feature offered by Stripe. <div id="card-e ...

What is the reason behind FieldSelect returning a string instead of an object like FieldCheckbox?

FieldSelect component from Sharetribe documents is giving me a string, while FieldCheckbox is returning a JSON object. In a specific scenario, I want FieldSelect to store a JSON object. How can I achieve this? Below is the code snippet for reference: I& ...

Presenting a ui-router modal while maintaining the parent state's refresh-free appearance

I have implemented a unique feature in my angular app called modalStateProvider. It allows me to easily have modals with their own URLs. // Implementing the modalStateProvider app.provider('modalState', [ '$stateProvider', function ...

Email address string loses the '+"' when using AJAX

My ajax code has been working well in most cases, but when I tried using it for updating user details on my page, I noticed that the ""+"" symbol was getting lost if used in an email address (such as <a href="/cdn-cgi/l/email-protection" class ...

Establish the following 13 steps to configure the initial server state and retrieve the client state

Currently, I have 13 applications and I am utilizing Zustand as my state manager. Below is a simple layout example: <MainProvider> <div className="min-h-screen flex flex-col"> <Navbar></Navbar> <main className ...

The console object in Chrome_browser is a powerful tool for debugging and

Having difficulty saving an amchart graph to the localstorage and retrieving the data successfully. https://i.stack.imgur.com/lJ3bJ.png In the original object, there is a mystery b, while in the new object, it appears as a normal object. In Internet Expl ...

What is the reason behind the browser not reusing the authorization headers following an authenticated XMLHttpRequest?

As I work on developing a Single Page Application using Angular, I have encountered an interesting challenge. The backend system exposes REST services that require Basic authentication. Surprisingly, while obtaining index.html or any of the scripts does no ...

Animate an image to the right when clicked, then return it to the left with a second click

Seeking help with animating a set of images to move individually 300px right on first click, and then 300px left when clicked again. I'm currently facing an issue where my code is not working. It could be due to A) syntax errors or B) the images not ...

What is the best way to generate multiple progress bars by leveraging a for loop?

Exploring the code snippet below, I've been creating a progress bar that reacts to specific data input in array form. However, the issue I've encountered is that the code only generates a single progress bar. How can I incorporate this into my f ...

Avoid including package-lock.json file in GitHub contribution history

After the release of npm v5.0.0, utilizing npm packages automatically generates a package-lock.json file when running npm install. In my situation, my package-lock.json document is almost 10,000 lines long. Npm advises that this file should be committed: ...

Leverage the power of express-session in your NextJS project

Currently, I am working on developing a login system using NextJS and MySQL. I am looking to implement sessions for user login, but I am unsure of how to integrate express-session with NextJS. Can anyone provide guidance on whether express-session can be ...

The displayed value in the text field remains constant even when the object's attribute is modified

My issue involves the Date Text Field component of Material UI. Whenever I pass an attribute from an object, the displayed value in the Text Field does not update even when the object attribute changes. const [data, setData] = useState({ title: new Da ...

Stop the replication of HTML/CSS styles during the extraction of content from a div

Is there a way to prevent the copying of CSS properties, such as font styles and sizes, when content is copied from a div? I want only the plain text to be copied to the clipboard, without any formatting applied. ...