Issue with Moment.js: inability to append hours and minutes to a designated time

I have a starting time and I need to add an ending time to it. For example:

start=19:09
end=00:51 // 0 hours and 51 minutes

I want to add the 51 minutes to the 19:09 to make it 20:00.

I've attempted several different methods as shown below, but none are producing the correct time.

I tried:

let [hour, minute] = end.split(':').map(Number);
this.end = Moment(start).add({ hour: 'hours', minute: 'minutes' }) // also tried .add(hour,'hours').add(minute,'minutes')

which still results in 19:09. It seems to be disregarding my end time.

I also tried:

Moment(end, 'hh:mm').add(Moment.duration(start)).format("hh:mm");

which gives me an output of 08:00 when it should be 20:00

What am I missing? I want to add the end time to a start time. Keep in mind that the end time is always changing, sometimes being 13:05, etc. because it's based on user input.

Answer №1

There are several key issues with the provided code:

  1. The practice of creating a moment using only a timestamp (e.g. moment('19:09') without a date) is now deprecated and will result in an error. To resolve this, it is necessary to enter a fully defined timestamp in RFC2822 or ISO format, or explicitly specify the input format to the library.

  2. In the object passed to the add() function, the values being passed in are as follows:

    {
      hour: "hours", 
      minute: "minutes"
    }
    

    This means instead of providing numerical values for hours and minutes to add to your moment instance, strings such as "hours" and "minutes" are being passed, which momentsjs cannot process.

  3. The format hh:mm restricts hours to be between 0 and 12. If you require a 24-hour clock, it is essential to use HH:mm.

When addressing these concerns, the code snippet below functions correctly:

let start = '2021-01-07 19:09', 
    duration = '0:51', 
    starttime = '19:09';

let [hour, minute] = duration.split(":");

//shorthand initialization for the argument
let endtime1 = moment(start).add({hour, minute}).toString(); 

//explicit definition of property names
let endtime2 = moment(start).add({hours: hour, minutes: minute}).toString(); 

//add hours and minutes separately
let endtime3 = moment(start).add(hour, "hours").add(minute, "minutes").toString(); 

//provide a format for the timestamp. momentsjs will take the current date for the date value
let endtime4 = moment(starttime, "HH:mm").add(hour, "hours").add(minute, "minutes").toString();

console.log(endtime1);
console.log(endtime2);
console.log(endtime3);
console.log(endtime4);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

It's also important to note that when specifying which part of the timestamp to manipulate, singular or plural terminology can be used. For example,

moment(...).add(4, "hour").add(17, "minute")
and
moment(...).add({hour: 4, minute: 17})

are equivalent to

moment(...).add(4, "hours").add(17, "minutes")
and
moment(...).add({hours: 4, minutes: 17})

as demonstrated in the snippet through the creation of endtime1 and endtime2

Answer №2

To accurately add time duration, ensure you convert it into a single unit such as minutes, seconds, or days. Once converted, use the snippet below.

Utilize moment methods for duration conversion

const mins = moment.duration(10, "hour").asMinutes();

const someTime = moment('19:09',"HH:mm");

const data = someTime.add('51','minutes').format("HH:mm")

//A more efficient solution would be
const data2 = someTime.add(1, "hours").add(51, "minutes").format("HH:mm")
console.log(data)
console.log(data2)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

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

What is the process of setting up a subelement in a Vue array?

I am currently working on incorporating an array read feature using Vue.js: {{ this.locations[this.record.carton.LocationID - 1].Location }} Although the code functions properly during runtime, it throws an error upon initial loading: app.js:55125 [Vue wa ...

I keep encountering the issue where I receive the message "Unable to access property 'innerText' of an undefined element" when running the Array forEach function. This problem seems to be happening within the HTMLInputElement section of the code

I am facing an issue where the error occurs because "cardTxt" is not recognized as a string. I verified this using typeof syntax, but I'm unable to understand why it can't be a string. This code snippet includes the use of bootstrap for styling. ...

Present a pop-up notification box with a countdown of 30 seconds prior to the expiration of a session timeout in JSF

Our task is to create a timeout window that appears 30 seconds before the session expires. If the user remains inactive, they will be automatically redirected to the home page. We already have the maximum allowed duration of inactivity defined. I would l ...

Next.js has a problem where it displays incorrect data when users navigate rapidly between pages

An unusual challenge has emerged while rendering data on a Next.js page in my application. Here's the scenario: I've created a Next.js page that showcases customer details based on a query parameter called cid. The page retrieves customer data an ...

Leveraging Next.js ISR to pass extra information to the getStaticProps function from the getStaticPaths

Inside SingleBlogPost.jsx, the code for generating blog pages by their slug is as follows: export async function getStaticPaths() { const res = await fetch("http://localhost:1337/api/posts"); let { data } = await res.json(); const paths = data.map(( ...

Is the parent component not triggering the function properly?

Hey there, I'm working with the code snippet below in this component: <app-steps #appSteps [menuSteps]="steps" [currentComponent]="outlet?.component" (currentStepChange)="currentStep = $event"> <div appStep ...

Experiencing issues with creating HTML using JavaScript?

I'm a JavaScript novice and struggling to figure out what's wrong with my code. Here is the snippet: var postCount = 0; function generatePost(title, time, text) { var div = document.createElement("div"); div.className = "content"; d ...

Ajax is displaying some unusual behavior

Currently, I am working on an ajax request to check if a specific combination of username or password exists. <script> $("form").submit(function(e){ e.preventDefault(); //send data to ajax file now $.ajax({ type: 'POST ...

Having trouble adjusting the width and height of images to a full 100% scale

I'm currently working on an Angular and Bootstrap application where I am trying to integrate a Bootstrap carousel. However, I've encountered some resizing issues with the width and height of the images/graphs. You can view a demo of the issue he ...

Utilize the context API to efficiently share information from the parent to both its children and sibling children

I'm currently working on displaying fetched data in a child component using the context API, but encountering an error in the browser: TypeError: render is not a function The above error occurred in the component: in AppDataList (at App.j ...

How to set return types when converting an Array to a dynamic key Object in Typescript?

Can you guide me on defining the return type for this function? function mapArrayToObjByKeys(range: [string, string], keys: { start: string; end: string }) { return { [keys.start]: range[0], [keys.end]: range[1] } } For instance: mapArrayToObj ...

What is the best method to make the first input field the focus in BootStrap?

Is there a way to prioritize the focus on the initial input element in an HTML form without specifying an ID? How to set the focus to the first input element in an HTML form independent from the id? I'm working with BootStrap and ASP.NET MVC4. De ...

Is requesting transclusion in an Angular directive necessary?

An issue has cropped up below and I'm struggling to figure out the reason behind it. Any suggestions? html, <button ng-click="loadForm()">Load Directive Form</button> <div data-my-form></div> angular, app.directive(&apos ...

What could be causing the React state to not function properly when using data from an external class?

Recently diving into the world of Javascript and React, I decided to challenge myself by creating a basic calculator. My strategy was to separate the calculator logic into its own class. As I am currently testing it out, I encountered a peculiar issue. It ...

Using jQuery to reload the page following a PHP form submission

Currently facing an issue as I am trying to load the same page submitted by PHP, specifically in a comment section. After users submit their message, I want to display the existing comments along with the new one. The problem arises because I'm not u ...

Is there a way to set the AutoComplete control in Material-UI as mandatory?

Yesterday was a frustrating day as I attempted to set the AutoComplete control as required. Unfortunately, the API lacks a required attribute and onNewRequest doesn't trigger if the textbox is empty. Additionally, onBlur has a glitch preventing it fro ...

Exploring ways to access elements within shadow-root (open) in Angular using SVG.js

I'm currently tackling a project involving Angular Elements. Within this specialized component, my goal is to incorporate SVG.js 3+. However, due to the necessity of utilizing ViewEncapsulation.ShadowDom in my component, I am encountering challenges w ...

Exploring the process of navigating between pages in Next.js using react-router-dom

Whenever a successful login occurs, I want to redirect the user to a different page. However, I am encountering an error message: https://i.sstatic.net/Wi8XW.png This is the snippet of code that is causing the issue: export default function SignUp() { ...

Issue with dynamic dropdown selection causing element to not display

My code is designed to call the addpoc() method on button click, which generates a set of input boxes and a dropdown. When the dropdown option personal/workmail is selected, an input box should appear based on the selection. The issue arises after the init ...

Switch the ng-bind-html option

Dealing with a string in my scope, I must determine whether I want the HTML escaped or not. A boolean value helps to decide if the HTML should be escaped or left as is. Snippet Check out some of my code examples below: $scope.result = "<b>foo</ ...