Leveraging Moment.JS to determine the variance between two dates represented in diverse formats

Currently, I am utilizing moment.js to determine the difference between two dates in my Qualtrics survey. The following code has been effective thus far. The dates are formatted as YY-mm-dd, and ultimately, I receive the variance in days.

const duedate= Qualtrics.SurveyEngine.getEmbeddedData('duedate');
const daystodue = moment(duedate).diff(moment(new Date()), 'days', false);
Qualtrics.SurveyEngine.setEmbeddedData('daystill', daystodue );

An issue arises when I switch the format for the embedded data 'duedate' from YY-mm-dd to ISO 8601 (for example, 2021-10-19T20:30:48Z) - this functionality ceases to work.

I understand that I may need to adjust the format for new Date() to ISO as well, or convert 'duedate' back to YY-mm-dd, but I am struggling to find a solution. Here is what I have attempted:

const duedate= Qualtrics.SurveyEngine.getEmbeddedData('duedate');
const daystodue = moment(duedate).diff(moment(new Date().format("YYYY-MM-DDTHH:mm:ssZ")), 'days', false);
Qualtrics.SurveyEngine.setEmbeddedData('daystill', daystodue );

I referred to this article for guidance, but as a novice in JavaScript, I am unable to make it function properly.

Any assistance would be greatly appreciated!

Answer №1

Moment.js demonstrates its intelligence by effortlessly handling and performing calculations with dates in different formats. I put this to the test, and it delivered:

const taskDeadline = '2021-10-19T20:30:48Z'
const yearStart = '2021-01-01'
moment(taskDeadline).diff(moment(yearStart), 'days', false)

This code snippet yields 291 as the result.

Disclaimer: The version of Moment.js used for this experiment was v2.29.1

Answer №2

After some tinkering, I managed to assemble the following code that seems to do the trick:

const deadline= Qualtrics.SurveyEngine.getEmbeddedData('deadline');
const currentDate= new Date( );
const daysLeft= moment(deadline).diff(moment(currentDate), 'days', false);
Qualtrics.SurveyEngine.setEmbeddedData('daysRemaining', daysLeft);

Big thanks to everyone for sharing your insights!

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 it possible to invoke the created() function in Vue from another method?

Currently, I am developing an application in Vue. Upon loading the page, a cookie containing the user's zip code is retrieved and used to perform a search. However, users should also have the ability to change their zip code if it is incorrect. I woul ...

Importing script files based on certain conditions

I am trying to dynamically import script tags based on a parameter set in the URL. Here is my current approach: function getURLValues(name) { var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location ...

The search feature in my React Pagination is not performing as effectively as expected

I recently set up a React app that interacts with a MongoDB database using an Express Server. The pagination feature is working smoothly, but I encountered an issue with the search function. It only works when typing in the input box; deleting characters d ...

In this scenario, the context is being revised and adjusted upon the second attempt

const {user, setUser} = useContext(UserContext); const {auth, setAuth} = useContext(AuthContext); const handleSubmit = async (e) => { e.preventDefault(); //axios request to the backend const url = 'http://localhost:5000/home'; ...

Having trouble with Axios communicating with the Scryfall API

Trying to fetch data with axios from this specific endpoint, but encountering unexpected errors: Oddly enough, the request returns data successfully when tested using Postman or a browser (GET request), but it's unresponsive otherwise. Here's t ...

Is array.push not functioning properly?

let teamMembers = []; response.team.members.forEach(async m => { let userResponse; try { userResponse = await axios.get(`https://api.hypixel.net/player?key=KEY&uuid=${m.uuid}`); } catch (err) { console.error(err); } ...

Chapter 5 of Eloquent JavaScript's 3rd Edition presents Exercise 3

I'm struggling with an exercise in the latest edition of a book, specifically in Chapter 5 which covers Higher-Order Functions. The prompt for the exercise is as follows: "Similar to the some method, arrays also contain an every method. This method r ...

Performing function in Vue.js when a change occurs

I recently started developing a Vue.js component that includes an input field for users to request a specific credit amount. My current goal is to create a function that will log the input amount to the console in real-time as it's being typed. Ultima ...

MongoDB Driver Alert: MongoError - Cursor Not Found. Cursor ID 7820213409290816 was not located in the specified namespace db_name.collection_name

Having successfully created a Nodejs API server that connects to AWS MongoDB (version: 3.6), everything seems to function flawlessly when calling one specific API endpoint (api/lowest). However, upon making multiple simultaneous calls to this API (15 in to ...

Initiating Fancybox through a hyperlink within the webpage - Explore a dynamic image collection featuring multiple albums

I have successfully created an image gallery with multiple albums, each containing a different number of photos. I am currently focused on implementing two fancybox features. Requirement 1: When the primary image of any album is clicked, a fancybox should ...

Prevent ng-click functionality for markers and infowindows on an Angular map

Currently, I am utilizing angular map and have bound an ng-click event to it which triggers a dialog window to open. However, I am facing an issue where I want to disable ng-click for markers and infowindows. This problem did not arise when I was using pla ...

Protractor - selecting a button within a table

Following the HTML code provided below, there is a table containing a list of test site links with a delete button next to each test site. /* Element locators in the table */ var testSiteLinks = element.all(by.css('a[ui-sref^="testpages"]')); ...

Why isn't the onChange function triggering in the input type text when the input is not manually typed in?

I am currently facing an issue with two text fields in my HTML form. Here is how they are set up: HTML : <input type="text" id="input1" onchange="doSomething();" disabled/> <input type="text" id="input2"/> JavaScript : function doSomething( ...

Maximizing the potential of AngularJS directives while maintaining a seamless connection to the controller

Is there a way to maintain the connection with the current controller when wrapping data with a directive? I am facing an issue where the directive within the wrapped template loses connection with the outside controller, making it impossible to execute f ...

Steps for swapping a term with a hyperlink

I am looking to substitute a word with a link instead, here's how I plan to accomplish it: const text = "Edit src/App.js and save to reload." return ( <div className="App"> <header className="App-header"&g ...

Problems with JQuery UI buttonset behavior

As I develop a UI application utilizing JQuery UI components, I encounter an issue with aligning radio buttons within the interface. While using JQuery buttonset in isolation functions correctly, integrating it with other UI elements causes misalignment: ...

Implementing meta tags in React.js

I am attempting to incorporate dynamic meta-tags on each page of my website. However, despite my efforts, I cannot seem to locate the meta-tags in the page's source code. Do I need to make adjustments in public/index.html, considering that I am not ut ...

What are some effective ways to grasp Wordpress custom functions?

I have a custom theme and came across the line <?php sg_header_js() ?>. I assumed that checking Wordpress's functions folder might provide more insight. Upon examining functions>function.php, I found the following code: <?php //Textdomai ...

The AngularJS component materializes almost instantaneously

Using AngularJS, I have developed an application where a certain section of code is displayed after the page loads for a split second: <div class="col-sm-4" data-ng-repeat="user in users"> <div class="card"> ...

Restrict the quantity of user responses with JavaScript

For this questionnaire, users are limited to selecting and ranking only 3 out of the 5 listed Social Apps. I am currently using questback to build the survey, but I require assistance in implementing a JavaScript condition. <table> <tr> & ...