What is the best way to find the difference between two time moments using Moment

Hello everyone, I could really use some assistance with Moment.js. I have two input fields, one labeled Start and the other labeled Stop.

start = moment().format('LT'); // This works when I click on the play button
stop  = moment().format('LT'); // It works when I focus on the counter input next to the play button --> for testing purposes

I am looking to manually change the start input field, so I need a validation function that checks if the input value is valid or not in the format LT. For example, if I delete the value '6:39 PM' from the input field as shown in the picture below and type '6:02:00 PM', '1:00 PM', or add a string like '5:dfds2 PM', I want to console log any error messages and revert back to the previous input value. Similarly, if I remove the current value and add a number like '1' without 'AM' or 'PM', it should determine whether the number comes before or after the stop input value and autofill the input field with '1:00 AM' or '1:00 PM'. I tried using the following function to validate the start input field but it's giving me incorrect results:

function validate(inputVal) {
  let temp = this.startTime;
  let x = temp;
  if(moment(inputVal, "hh:mm").isValid()) {
    x = moment(inputVal, "HH:mm").format('hh:mm A');
    console.log("inputVal is: " + inputVal + " and x is: " + x);
    this.startTime = x
  } else {
    this.startTime = "temp";
    console.log("no");
  }
}  

Here is the image: https://i.stack.imgur.com/3eOOQ.png For more information, you can visit the Toggl website, where my idea was inspired from. Any help would be greatly appreciated! Thanks in advance.

Answer №1

I revised and simplified your function to make it more efficient. All you need to do now is double-check the moment format to ensure it meets your requirements

function checkValidity(input) {
    let parsedInput = moment(input, "hh:mm");
    if (parsedInput.isValid()) {
        this.startTime =  parsedInput.format('hh:mm A');
    } 
}  

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 proper way to reference an EJS function that is declared in a different EJS file?

document 1: jsfunction.ejs <% function testFunction() {return 42;} %> file 2: data.ejs <% include jsfunction.ejs %> <% testFunction(); %> result: ReferenceError: 1| <% include jsfunction.ejs %> >> 2| <% testFuncti ...

Ways to iterate through a JSON formatted array variable using JavaScript

Below is my code snippet, used to plot all the locations fetched from my database onto a Google map. $.ajax({ url:"http://localhost/church_finder/index.php/MapController/search_church", type:'POST', data: ...

Attempting to grasp the sequence in which setTimeout is ordered alongside Promise awaits

I've been puzzling over the sequence of events in this code. Initially, I thought that after a click event triggered and Promise 2 was awaited, the for loop would resume execution once Promise 1 had been resolved - however, it turns out the outcome is ...

What is the best way to eliminate the space underneath a graph?

Despite trying multiple solutions, I'm still struggling to remove the excess blue space below the graph that appears when clicking the submit button. Any insights into what might be causing this issue? JSFIDDLE Below are the CSS styles related to t ...

The browser encountered an issue trying to load a resource from a directory with multiple nested levels

I've stumbled upon an unusual issue. Here is a snapshot from the inspector tools. The browser is unable to load certain resources even though they do exist. When I try to access the URL in another tab, the resource loads successfully. URLs in the i ...

Blend the power of Dynamic classes with data binders in Vue.js

Recently, I've been working on a v-for loop in HTML that looks like this: <ul v-for="(item, index) in openweathermap.list"> <li>{{item.dt_txt}}</li> <li>{{item.weather[0].description}}</li> <li>{{item.w ...

The file browser fails to open following an AJAX request in the Firefox browser

I am encountering an issue where the programmatic click on a file input does not open the file browser in Firefox after a successful AJAX call, although it works perfectly in Chrome. The problem persists on version 82.0.3 (64-bit) of Mozilla Firefox for Ub ...

Outputting a variable using javascript

My challenge is to efficiently print the contract variable, which contains HTML content fetched from the server. How can I achieve this easily? I want the print window in Chrome to display the document with the contents of my variable when I click a button ...

Having trouble getting Jquery Ajax Post to work properly when using JinJa Templating?

Objective: My goal is simple - to click a button and post information to a database. Problem: Unfortunately, clicking the button doesn't seem to be posting to the database as expected. Setup: I am working with Flask Framework, Jquery, and Jinja Temp ...

What is the best way to organize large amounts of data into an array?

I am currently working on developing a unique version of wordle using javascript and html. In order to do this, I require a comprehensive list of all possible wordle words stored in an array format. Although I have the words listed within a document contai ...

Tips on changing an image with a button click

I am currently working on a project where I have a div tag containing an image that is selected randomly from different arrays based on topics. However, I am facing some challenges in making the image change when the "go" button is clicked. I want the if ...

Transforming the mui stepper connection into a progress bar is simple. Each step contains individualized content to guide you through the process

Is there a way to make the MUI stepper connector act as a progress indicator? I have step content and connectors as separate divs, but I'm having trouble styling them. Any assistance would be greatly appreciated! ...

Ways to modify the screen when a click event occurs

To make the display block when clicking this icon: <div class="index-navi-frame-box"> <p onclick="expandFunction()"> <i class="fa fa-bars"></i> </p> </div> Here is what it should change to: <div class=" ...

Utilizing encoding and decoding techniques in PHP and JavaScript with robust data attribute validation

I am utilizing data attributes to transfer information from HTML to JavaScript. The data attributes are derived from MySQL data, so they may contain spaces, resulting in validation errors since spaces are not permitted within attributes. My proposed solut ...

Bringing in a selection of functions as an object using ES6 imports

functions.js export const setA = () => {...} export const setB = () => {...} export const setC = () => {...} component.js import {setA, setB, setC} from 'functions' export class componentOne extends React.Component { constructor(p ...

Navigating through Index in #each in emberjs

Take a look at the code provided below: http://jsbin.com/atuBaXE/2/ I am attempting to access the index using {{@index}}, but it doesn't seem to be compiling. I believe that handlebars should support this feature: {{#each item in model}} {{@index} ...

Why is there a node_modules folder present in the npm package I authored when using it as a dependency in another module?

After successfully launching my first npm package, I noticed something strange when installing it as a dependency in my project. Upon exploring the project folder in node_modules, I discovered an unexpected node_modules folder containing just one package ...

Functionality that can be utilized repeatedly

I've been struggling to implement a feature for repeatable blocks in my web form. The issue I'm facing is that when I click the buttons, nothing happens even though they work fine when tested in the console. I've been stuck on this problem f ...

Is there a simple method in JavaScript to combine, structure, and join numerous multi-dimensional arrays in a specific manner (from right to left)?

Looking for a simple solution to merge, flatten, and concatenate multiple multi-dimensional arrays in JavaScript in a specific manner (from right to left) # Example [['.class1', '.class2'], ['.class3', ['.class4', & ...

The loading cursor in IE7 flickers incessantly, causing the webpage to lag and become un

When I move my cursor and click in text fields, the page becomes unresponsive and shows a wait cursor. If you're curious to see this issue in action, check out this video. This problem is specific to IE7. I've attempted to identify any ajax re ...