If the duration is 24 hours, Moment.js will display 2 days

Looking for a way to allow users to input specific timeframes? For example, 1 week or 5 days and 12 hours. I found that using Duration from Moment.js seemed like the best solution.

The snippet of code below is currently giving me 2 00:00, indicating 2 days instead of the expected 1 day due to there only being 24 hours in the timeframe.

moment.utc(moment.duration(24, 'hours').as("milliseconds")).format("D HH:mm");

Any ideas on what might be going wrong here?

Answer №1

When you use moment.utc(...), you are establishing a millisecond offset of 24 hours from the Unix epoch (1970-01-01). Essentially, your moment object represents the date 1970-01-02 00:00, and when you print it out, you are only displaying the day part.

Answer №2

When you have control over the time frames, you have the flexibility to input the desired duration in milliseconds manually. For instance, 24 hours can be expressed as 86400000 milliseconds.

Answer №3

To properly format the milliseconds in a moment duration, you should use moment.duration instead of moment alone. Below is the line of code that will give you the desired output:

 moment.duration(moment.duration(24, 'hours').as("milliseconds")).format("D HH:mm");

The answer to your query is: 1 day 00 hours and 00 minutes.

Answer №4

After some troubleshooting, I managed to resolve the issue by using the code snippet below along with a helpful plugin:

moment.duration(moment().diff(moment().subtract(1, 'days')));

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

Retrieving data within specific date boundaries

How can I retrieve all records within a specific month from a database? For example, if the records in the database are: 01/08/2014 02/08/2014 03/08/2014 04/08/2014 05/08/2014 14/08/2014 05/09/2014 16/09/2014 I only want to select records between 01/08/ ...

What is the process for creating a two-column table in Angular?

Currently, I have an Angular template code that displays the header on the left and data on the right in a top to bottom layout. <div class="panel-body"> <table class="table table-striped"> <tr ng-repeat="f in fields"&g ...

An incessant stream of onclick events is being triggered

My HTML code consists of a jQuery script and a button that triggers a function to display random answers. However, after clicking the button once, the answers cycle automatically without any input. I want each click to show a different answer. What could ...

Unable to find '/images/img-2.jpg' in the directory 'E:React eact-demosrc'

My code is giving me trouble when trying to add an image background-image: url('/images/img-2.jpg'); An error occurred during compilation. ./src/App.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src?? ...

Capturing member function details using JSDoc

Here's the code snippet I'm working with: /** This class blah blah... @constructor **/ my.namespace.ClassA = function(type) { /** This function performs an action **/ this.doSomething = function(param){ } } The class will be inc ...

Seamlessly transition between various states within a React component for a fluid user experience

I'm currently working on a simple component structured like this: var component = React.createClass({ render: function(){ if (this.props.isCollapsed){ return this.renderCollapsed(); } return this.renderActive() }, ren ...

Photo captured by camera is not stored in photo gallery

I am currently working on a basic image upload form that allows users to take photos using their phone camera and upload them. However, I have noticed that the pictures taken this way are not being saved to the gallery. Is there something missing in the H ...

Is it advisable to prevent Set and Map from having unspecified generics in TypeScript?

Upon reviewing some old code that I wrote, I realized that I had neglected to specify a generic type for a Set. The type was set as Set<unknown>. Strangely, despite this, I found that I could still utilize all the methods of the Set without encounter ...

Why does getElementById work when getElementsByClassName doesn't?

I created a script with the purpose of hiding images one and two, while keeping image 3 visible and moving it into their place. The script functions correctly when using div Id's instead of div Classes. However, I prefer to use div classes for groupin ...

It appears that the crackling noise is being generated by AudioContext.decodeAudioData

I am currently in the process of developing an electron app that enables users to cut and rearrange multiple audio samples while seamlessly playing them back. The combined duration of these samples can exceed an hour, making it impossible to decode and sto ...

Alter the configuration of a JSON object

I'm currently working on modifying the following JSON text. It has the structure as shown below: { "cabecera": { "tipo_cambio": "", "fecha_emision": "", "total": "" }, "detalle": { "940b130369614bd6b687dc5b41623439": { " ...

Switch between visibility of objects with toggle button

I have set a background image on the body, and positioned a large box, footer, navigation bar, and header above it. In order to add functionality to slide these elements up and down, I've created two buttons with classes 'slideUp' and &apos ...

Enhancing JavaScript Arrays by incorporating data from a JSON file

Could you kindly advise me on what I might be doing incorrectly here? It seems like a simple issue, but it has taken up the entire day. All I wanted to do was add a value to an array called messages from a JSON file. function get_message(params) { va ...

Exploring the focus() method of refs in Vue 3

I'm struggling to comprehend why my straightforward test case keeps failing. As I delve into the world of testing in Vue, I've created a simple test where the element.focus() is triggered onMount(() => /* see implementation ...

Retrieve text from the input field after a brief pause following each keystroke for uninterrupted typing

I am currently facing an issue with a form that is submitted remotely whenever the elements change. Specifically, when a user types in the search field and hits a key, the form gets submitted multiple times even though only the final submission matters. I ...

Calculating tables dynamically with jQuery

I have encountered an issue with my dynamic form/table where newly added rows are not being calculated correctly. While the static elements function as expected, the IDs and classes of the new rows do not align with the calculation logic. Can someone offe ...

Delete Entries in MongoDB Collection According to Unique User Pairs

I have a collection of messages stored in MongoDB and I need to keep only the latest 500 records for each pair of users. Users are identified by their sentBy and sentTo attributes. /* 1 */ { "_id" : ObjectId("5f1c1b00c62e9b9aafbe1d6c&quo ...

The webpage continues to refresh after executing a JavaScript function triggered by the AJAX response

I have experimented with various solutions for calling a JavaScript function returned from an AJAX response. While each method worked to some extent, I found that using an alert within the refreshResults function was necessary in order to display the resul ...

Utilize ng-bootstrap in an Angular CLI project by integrating it with npm commands

I've been attempting to set up a project using Angular CLI with ng-bootstrap, but I'm having trouble getting the style to work properly. Here are the exact steps I followed (as outlined in the get-started page): Create a new project using `ng n ...

What is the correct RegEx pattern I should use to properly match the provided test case without including the ending period?

Regular Expression: /@([\S]*?(?=\s)(?!\. ))/g Given String: 'this string has @var.thing.me two strings to be @var. replaced'.replace(/@([\S]*?(?=\s)(?!\. ))/g,function(){return '7';}) Expected Result: ...