Using moment.js to perform addition of time does not yield the desired outcome

Every time I try to

---- make changes ----

var someMoment = moment('6:30 PM', ["h:mm A"]);

---- end changes ----

someMoment.add(30, 'minutes')  

I am not getting any desired outcome.

console.log(start); -- Moment {_isAMomentObject: true, _i: "6:30 PM", _f: "h:mm A", _isUTC: false, _pf: Object…}
console.log(start.add(inc, 'minutes')); --Moment {_isAMomentObject: true, _i: "6:30 PM", _f: "h:mm A", _isUTC: false, _pf: Object…}

According to the documentation, the add function should modify the specified moment, so the above code should work, but I have also attempted

var end = start.add(inc, 'minutes')
console.log(end); --Moment {_isAMomentObject: true, _i: "6:30 PM", _f: "h:mm A", _isUTC: false, _pf: Object…}

what I can do though is this

console.log(start.add(inc, 'minutes').format("h:mm A")); --7:00 PM

My goal is to take a moment, add 30 minutes to it and, preferably have a new moment that is 30 minutes ahead, or at least have the initial moment be 30 minutes ahead.

I know I can take the format output and create a new moment, and I might have to do that, but this seems somewhat flawed.

---- make changes ----

using moment 2.1

I am experiencing this issue within a method in my application, I haven't isolated it in a jsfiddle or anything, but the method takes a string and an increment. I suppose I'll paste it here

here i'm trying one way but I've also tried using the modified start and cloning the start

var timeIsBetweenStartInc = function(_target:string, _start:string, inc:int){
var target = moment(_target, ["h:mm A"]);
var start = moment(_start, ["h:mm A"]);
console.log(start);
var end = moment(start).add(inc, 'minutes');
console.log(end);

return target.isBetween(start, end, 'minutes', '[)');(target, start, end);
};

---- end changes ----

Answer №1

It appears that Moment.js is functioning as intended, but console.log may not be displaying the information as expected. Instead of showing the object's state at the time of calling log(), it displays a reference to the object at the time of consultation. To see the difference, consider using console.dir(). Alternatively, you could use JSON.stringify() to obtain a string representation of the object, or try calling format() on the Moment object.

Answer №2

If you're looking to manipulate time using Moment.js, you can take advantage of the clone method. Here's an example of how you can do this:

var current = moment(),
    futureTime = current.clone();

Once you've cloned the current moment, you can then add a specific amount of time to it like so:

futureTime.add(30, "minutes");

By comparing the UNIX timestamps of the two moments...

futureTime.unix() - current.unix();

You'll see that they are 1800 seconds, which equals 30 minutes, apart.

Answer №3

It seems like you are relying on internal properties of the Moment objects (_i) to hold the adjusted time. It could be that changes are applied lazily, or that these internal values are tracking the original time, but once you perform a method on the object (such as calling .format()), the adjusted time is displayed.

UPDATE: Alternatively, you might be using an outdated version of Moment.js. Version 1 seems to display a similar behavior to what you are experiencing. However, it appears that you are referring to the most recent (v2) documentation, hence the difference between the documentation and the actual behavior you are observing.

My goal is to create a moment, add 30 minutes to it, and ideally have a new moment that is 30 minutes ahead, or at least have the original moment be 30 minutes ahead.

var start  = moment();
var end    = moment(start).add(30, 'minutes');

console.log( start.toString() );
console.log(   end.toString() );

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

Problem: Vue 3 build does not generate service worker

After adding the "@vue/cli-plugin-pwa": "^4.5.12" to my package.json and setting up workbox configuration in my vue.config.js, I encountered an issue. When running npm run build:prd with the script vue-cli-service build --mode prod.exam ...

AngularJS Issue: Duplicate Error

Attempting to refresh data after making some changes results in duplicate errors appearing within the ng-repeat. The scenario is as follows; I am working on creating a dynamic menu module The requirements include adding, deleting, changing the order, an ...

The react component is not defined within the <Popup></Popup> tag

SOLVED: Big thanks to everyone who offered their assistance. Upon further investigation, I discovered that in the library I was using, the trigger={} functionality is specifically designed to work only with a button element. To address this issue, I took ...

Send the context parameter value of Unified Service Desk to a JavaScript web resource in CRM

Currently, I am working on CRM 8.2 and Unified Service Desk 4.1. I have a specific requirement where I need to pass parameter values from within Unified Service Desk Data Parameters to a JavaScript Webresource. I have come across some resources that sugge ...

What is the method for storing elements in localStorage within a ReactJs application?

Currently, I am working on learning react-redux and coding a new project. My goal is to implement a feature where clicking the Add Favorites button will push all column data to local storage. Despite reading numerous articles, none of them have provided ...

The clash between two jQuery plugins featuring identical function names

I have encountered a dilemma while working on a large website that includes two conflicting jQuery plugins for autocomplete functionality. The first plugin is jquery.autocomplete.js (not part of jQuery UI) which defines the autocomplete function like this ...

Ionic - numerical age selector control

Currently working on a hybrid mobile app and ran into a specific issue. I'm in the process of adding new items to my left side menu, including an age number spinner component (min:18, max:65). After searching through various sources and Ionic documen ...

Ensure that only the dropdown menu that is clicked within a Vue loop opens

Hey, I'm having an issue with my dynamically created drop-down menus. I can display them correctly using v-Show, but the problem is that when I click on one element, they all open below my code. <div :class="{inizio : utenteAttivo.nome === con ...

Working with AngularJS: Accessing a JSON file from the local directory

The answers to my previous questions on this topic have not been satisfactory. It seems that most examples and tutorials for AngularJS online always define tiny JSON arrays directly inside the JavaScript code... So, let's simplify things with a basi ...

What is the process for creating an xpath for hyperlinks with the 'contains text' attribute?

I am in need of creating Xpath for links based on contained text. I have devised the following code to achieve this, however, a scenario arises when there are three links named 'Entity', 'Entity Type', and 'Entity Group'. If I ...

Axios is passing an array instead of a JSON object when making a POST request

I am trying to make a post request using axios in my Vue.js front-end to communicate with Laravel on the backend. const data = { file: {id} } axios.post('api/documents/remove', data).then((response) => { ...

using spread operator to extract properties from API response objects

Currently undergoing a React/Next course, we recently had to retrieve data from an API that returns a list of objects containing information to populate the page. This task was accomplished using Next's getStaticProps method, passing the data to the ...

Unable to open file after downloading via AJAX

I am facing an issue while trying to download a file using an Ajax request. Although the file is successfully downloaded, I am unable to open it. I am seeking assistance with the provided details below. Thank you. On a JSP page, there is a list ...

Is it possible to await the response of a request in Socket.io with socket.on('answerToRequest')?

Can the following scenario work out? async function checkSocketStatus(){ socket.emit('checkOtherSocketStatus', otherSocketId); await socket.on('responseCheckSocketStatus', (status)=>{ console.log('status'); } ...

I am experiencing a 404 error when attempting to import a local JS file in Angular

After creating a new project with "ng new xxx", all you need to do is add one line of code in index.html: <!doctype html> <html lang="en> <head> <meta charset="utf-8> <title>Bbb</title> <base href="/&g ...

Is there a way for me to achieve a vertical page turning effect on a single page?

I am seeking to develop a unique calendar display consisting of 12 images that give the illusion of flipping up when clicked. While I am aware of turn.js, my knowledge of javascript is limited and I need guidance on how to proceed. Despite having a program ...

Default exports are not supported in TypeScript

I'm encountering issues with my Laravel + Vite + Vue 3 project. I followed the installation instructions in the documentation and everything works fine when the project is separated from Laravel and Vite. However, I'm facing a problem where TypeS ...

Unable to execute JS script to navigate back to prior page with webdriver

Here is my code snippet: JavascriptExecutor jse = (JavascriptExecutor)driver; jse.executeScript("window.history.go(-1);"); The code above isn't working. I've tried casting the webdriver instance but it doesn't work every time. I prefer not ...

"Unexpected behavior: NextAuth is failing to return defined custom scopes

I am currently working on a NextJS project that utilizes NextAuth. Initially, everything was functioning properly with the default scopes. However, my project now requires additional claims, which are listed in the supported scopes here. "scopes_supporte ...

FullCalendar displaying inaccurate dates and times

In my ASP.NET MVC application, a full calendar element is displayed as shown below: https://i.sstatic.net/hyAMo.png Here is the JSON data returned by the server through an ajax call for the month of January 2016: [{"id":17,"title":"39/2015 - Site meetin ...