Working with time durations in Moment.js to manipulate datetime

How can I properly combine the variable secondsToMinutes with the startdate?

The value of secondsToMinutes is "3:20" and the startDate is "2:00 PM". The desired endDate should be "2:03:20 PM". Despite my efforts, I keep encountering errors every time I attempt to achieve this.

   var startdate = data.StartTime;
   startdate = moment(startdate).format('LTS');

   var secondsToMinutes = readableDuration(self.runlength());//='3:20';

   var seconds = secondsToMinutes.split(':')[1];
   var minutes = secondsToMinutes.split(':')[0];

   var date = moment(startdate)
        .add(seconds, 'seconds')
        .add(minutes, 'minutes')
        .format('LTS');

However, the date appears as an invalid date.

Answer №1

moment().format("LTS") will give you a string value in the format of hh:mm:ss AM/PM. If you are creating a moment object using a non-standard format string, make sure to provide the input format as the second parameter in the moment constructor.

For example, the string Jan 1, 2017 represented as 01012017 is not standard. If you try to create a moment object using moment("01012017"), it will result in an "Invalid Date" response. Instead, use moment("01012017","DDMMYYYY")

var d = moment("01012017")
d.toISOString() => "Invalid date"

var d = moment("01012017", "DDMMYYYY")
d.toISOString() => "2016-12-31T18:30:00.000Z"

When creating the 'date' variable in your code, make sure to include "hh:mm:ss A" as the second parameter in the moment constructor like this:

   var date = moment(startdate, "hh:mm:ss A")
        .add(seconds, 'seconds')
        .add(minutes, 'minutes')
        .format('LTS');

Answer №2

The documentation for Moment is top-notch. For more information, be sure to visit: http://momentjs.com/docs/

To directly address your question, here is a potential solution:

var time = '3:20';
var seconds = time.split(':')[1];
var minutes = time.split(':')[0];

var newTime = moment(...)
              .add(seconds,'seconds')
              .add(minutes,'minutes')
              .format('LT');

It is advisable to utilize the appropriate methods provided. While there are advanced options for working with durations, this approach is concise.

Update:

Another user mentioned:

 moment('2:00:00 PM', 'h:mm:ss A')

This syntax may be necessary for a specific time format. Nonetheless, manipulating time using moment objects is straightforward. Remember to handle invalid inputs gracefully when working with moment objects. ;)

Answer №3

When attempting to parse the value '2:00:00 PM' in the last moment() call, it is important to note that using String + Format is recommended for anything other than ISO 8601 strings:

To ensure consistent results when parsing non-ISO 8601 strings, it is advised to use String + Format.

For instance, if you try:

var date = moment('2:00:00 PM')
    .add(30, 'seconds')
    .add(2, 'minutes')
    .format('LTS');

The date will be shown as Invalid date. However, by including the format h:mm:ss A as a second parameter:

var date = moment('2:00:00 PM', 'h:mm:ss A')
    .add(30, 'seconds')
    .add(2, 'minutes')
    .format('LTS');

... the resulting value will be 2:02:30 PM.

Answer №4

The .add operation in moment.js is no longer supported. Consider using dayjs for similar functionality.

Example: dayjs.add(1, 'day')

For more reasons to migrate from moment.js:

Answer №5

I originally tried a different approach, but ultimately found success with the following method:

// Initially, I stored the current time in the variable 'startTime'

let startTime = moment().format('HH:mm:ss');

// To manipulate the time, I added 10 seconds (this could also be done with minutes or hours) to the initial time:

startTime = moment(startTime ,'HH:mm:ss').add(10,'seconds').format('HH:mm:ss');

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 AJAX call failed because the web service was not properly configured, resulting in a missing parameter value being

I'm encountering an issue with my ajax call that displays a specific message. [WebMethod(EnableSession = true)] public static string UpdateTotalPrice(List<TicketPriceAjax> jsonTickets) { // conducting server-side processing return "a u ...

Automated scrolling within a div when an li element overflows

Looking to implement automatic scrolling in a div. I have a list of elements within a fixed height div, and now I want the div to scroll automatically when I press the down key after highlighting the 3rd li element (i.e Compt0005). Can anyone help me solve ...

The dangers posed by vulnerabilities in the React library

Hi there, I just finished setting up react-redux and noticed some vulnerabilities showing up in my console - both low and high. Can anyone explain what this means and if I should consider uninstalling it? ...

What is the best way to obtain a list of all the modules that are currently accessible in AngularJS

When declaring an Angular module, I specify its dependencies as follows: const myModule = angular.module("MyModuleName", ["Dep1", "Dep2", "Dep3"]); Each dependency comes with its own set of dependencies, directives, controllers, etc. Is there a way to qu ...

What is the best way to eliminate the hash from the URL of a single-route Angular application without the need for ui.router?

I came across a question that has been asked before on Stack Overflow, but unfortunately, it remains unanswered and without any comments. In my Angular app, I am working with a single route and I want to find a way to eliminate the # from the URL. If I h ...

Unable to sort nested JSON data in ngTable

I have successfully built an angularjs application using ngTable, however, I am facing an issue with sorting. The JSON structure is nested but the values are appearing correctly in the table. If anyone has a solution to this problem, please let me know. ...

Retrieve the element (node) responsible for initiating the event

Is there a way to identify which element triggered the event currently being handled? In the following code snippet, event.target is only returning the innermost child node of #xScrollPane, with both event.currentTarget and event.fromElement being null. A ...

Is there a way to retrieve data from three different Bookshelf.js models in a single query?

Three tables are in my database: User, UserDrink, and VenueDrink Here is a preview of the sample data: User id | name | gender | -------------------- 1 | John | male | 2 | Jane | female | UserDrink id | count | user_id | venue_drink_id 1 | 3 | ...

Is there a way to update the content of both spans within a button component that is styled using styled-components in React?

I am interested in creating a unique button component using HTML code like the following: <button class="button_57" role="button"> <span class="text">Button</span> <span>Alternate text</span> ...

The error message "Vue.JS computed from VueX Store is not recognized" is displaying

Within my Vuex store, I am able to see it in the Vue Devtools tool. However, when attempting to load data into a computed property, an error message stating that it is not defined is displayed. computed: { userData(){ return this.$store.state.use ...

Utilize obj in three.js to enhance your 3D

As someone new to three.js and 3D graphics in general, I am struggling with loading a high-definition OBJ file onto the screen. While I have been able to load the file, it is not as well-defined as I would like. The OBJ file in question is a ring with pea ...

Sending information from ngRoute resolve to the controller

I am currently working on an application that utilizes ngRoute to create a Single Page Application. One of the requirements is to ensure that the view is not loaded until the data has been successfully fetched from the database. While I have managed to ach ...

use javascript or jquery to conceal the textbox control

Looking to conceal a textbox control using javascript or jquery. I attempted the following code: document.getElementsByName('Custom_Field_Custom1').style.display="none"; Unfortunately, I received an error in the java console: document.getEle ...

Navigating through a diagonal path

Struggling to craft a diagonal navigation system similar to the images below. Despite its seemingly simplicity, I'm stuck investing too much time in figuring it out. My goal is for the menu container to smoothly reveal from right to left when clicking ...

Is the JSON parsing issue being caused by Bodyparser?

I am encountering an issue with parsing JSON on my server using the body-parser NPM module and Express. The JSON data is not appearing correctly on the server for some reason. Here is a snippet of my server code: ... app.use(bodyParser.json()); app.use(bo ...

What could be the reason why I am unable to choose my radio button? What error am I

The output can be found here... I am struggling to use a radio button and cannot seem to select it. Can someone please explain what issue I am facing? Any help would be greatly appreciated. const [value, setValue] = React.useState({ yes:"", no:"" ...

Here is a unique version of the text: "Implementing a JavaScript function in Angular to activate the data-bs

Attempting to use JavaScript in angular to close/hide a bootstrap5 modal, encountering an issue where the hide function in bootstrap is not working. When manually clicking a button with data-bs-dismiss attribute, it closes the modal as expected, but when t ...

What are the steps for sorting objects in an array by their data type attribute?

I am currently working with a JavaScript array of people objects that is dynamically rendered from JS. My goal is to implement a filter on the objects based on the selection made in the dropdown menu and matching it with the department attribute specified ...

My Angular JS http.get request is failing to reach the specified URL

While working with AngularJS to integrate RESTful web services into my website, I am encountering an issue where I am consistently receiving errors instead of successful responses. I have been stuck on this for the past three days and any assistance would ...

I'm facing some difficulties in sourcing my header into a component and encountering errors. Can anyone advise me on how to properly outsource my header?

Looking to streamline my headers in my Ionic 4 project by creating a separate reusable component for them. Here's how I set up my dashboard page with the header component: <ion-header> <app-header title="Dashboard"></app-he ...