Determining the time gap in milliseconds between two specified times using the "DD/MM/YYYY HH:mm:ss:ms" format in JavaScript

I have a situation where I need to calculate the time difference between two timestamps.

Starting time: "2014/10/28 11:50:28:318"

Ending time: "2014/10/28 11:50:35:249"

To achieve this, I utilized moment.js for the calculation. Here is my code:

var msElapsedTime = moment(EndTime , "DD/MM/YYYY HH:mm:ss:sss").diff(moment(StartTime , "DD/MM/YYYY     HH:mm:ss:sss"));

The result shows as milliseconds, but it seems to be rounded off.

Answer №1

When working with moment.js, it is important to use the correct parsing token for milliseconds, which is SSS, not ms or sss. Additionally, ensure that your date tokens are in the correct order.

var StartTime = "2014/10/28 11:50:28:318",
    EndTime   = "2014/10/28 11:50:35:249";

var msElapsedTime = moment(EndTime, "YYYY/MM/DD HH:mm:ss:SSS").diff(moment(StartTime , "YYYY/MM/DD HH:mm:ss:SSS"))

alert(msElapsedTime); // 6931

Answer №2

Check out this piece of JavaScript code:

var startTime = new Date("2022/10/15 09:20:45:123");
var endTime = new Date("2022/10/15 09:21:02:987");

console.log(endTime - startTime); // 17764

JSFIDDLE.

Answer №3

Here's how you can build it:

let timeDifference = moment('2014/10/28 11:50:28.318').diff(moment('2014/10/28 11:50:35.249'));

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

Can props.children be given a ref without any existing ref?

Consider this scenario... MainComponent.js <Wrapper> <p ref={React.createRef()}>{state.item1}</p> <p>{state.item2}</p> <p>{state.item3}</p> <p>{state.item4}</p> </Wr ...

Instructions on how to implement a readmore button for texts that exceed a specific character length

I am attempting to display a "Read more" button if the length of a comment exceeds 80 characters. This is how I am checking it: <tr repeat.for="m of comments"> <td if.bind="showLess">${m.comment.length < 80 ? m.comment : ...

Strange issue with Firefox when utilizing disabled attribute as "disabled"

I found a curious bug in Firefox: Check out (unfortunately not reproducible in jsfiddle) <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> < ...

What are the ways to implement global functions in Vue.js?

I have a function that formats dates without time. I want to reuse this function in multiple components. What is the recommended approach for handling this scenario? Should I use directives, filters, or another method? How should I go about defining this ...

Issue encountered: Unable to locate module: Error - Unable to resolve '@cycle/run' with webpack version 2.2.1

I am attempting to run a hello world application using cycle.js with webpack 2.2.1. The following error is being displayed: ERROR in ./app/index.js Module not found: Error: Can't resolve '@cycle/run' in '/Users/Ben/proj/sb_vol_cal ...

Create an AngularJS directive that formats the model value for visual display, while retaining the original value in the model

I am facing a challenge in building an AngularJS directive for a currency textbox. The directive should take values (amount and currency code) from the model in the scope and then apply currency formatting to it. I am struggling to build this directive usi ...

Utilizing Multiple Canvases Simultaneously

I'm facing an issue where I need to crop multiple images on a single page using the canvas tag in HTML5 along with JavaScript. However, only one image is displaying on the page. How can I resolve this? The code snippet that I have attempted is provid ...

Utilizing JSDoc for establishing an index signature on a class in ES6

When working with JSDoc, achieving the equivalent of Typescript's computed property names can be a challenge. In Typescript, you'd simply define it like this: class Test { [key: string]: whatever } This syntax allows you to access these comput ...

How can I create a rectangular border around text using the HTML5 canvas?

How can I dynamically draw fitted rectangles around text labels (person's full name) without fixed sizes, taking into account that the labels vary in lengths? Below is the code used to draw the text labels: var ctx = document.getElementById('ma ...

Encountered an error: Unable to access property '0' of an undefined variable

Below is the script I am using: <script> var count; var obj; function search() { xhr = new XMLHttpRequest(); xhr.open("GET", "test.json", true); xhr.send(null); xhr.onreadystatechange = function() { if (xhr.readyState == 4 & ...

A helpful tip for dynamically adjusting the canvas size is to utilize its height and width attributes to resize it whenever it undergoes a change

I am encountering an issue with the canvas element in my code. The canvas is supposed to update whenever its containing div is resized. window.addEventListener('resize',function() { let mapwidth = $('.canvas').attr("width") l ...

Jquery cascading menu

I'm currently experiencing difficulties in creating dropdown menus using jquery and css. Below is my HTML code: <nav class="topNav"> <ul> <li> <a href="#menu" class="menu-toggle"><img src ...

Unable to view sidebar navigation on the screen

I've been experimenting with the sidebar navigation from w3 schools, specifically trying to create a side-nav that opens from one div. You can see an example here: http://www.w3schools.com/w3css/tryit.aspfilename=tryw3css_sidenav_left_right&stack ...

Make sure to allow the async task to complete before beginning with Angular JS

As I develop an app using MobileFirst v8 and Ionic v1.3.1, I encounter issues with timing in my code execution. Specifically, when the application initiates, the regular ionic angular code within my app.js file runs. This section of the code handles the i ...

How can the Singleton pattern be properly implemented in Typescript/ES6?

class Foo{ } var instance: Foo; export function getFooInstance(){ /* logic */ } or export class Foo{ private static _instance; private constructor(){}; public getInstance(){/* logic */} } // Use it like this Foo.getInstance() I would ...

Prevent Fixed Gridview Header from being affected by browser Scroll-bar using JQuery

Is there a way to make the fixed header responsive to only one scroll bar in JQuery? Specifically, is it possible to have it respond solely to the div's scroll bar and not the browser's scroll bar? I attempted to remove the browser's scroll ...

Using Selenium in Java, one can wait for a JavaScript event (such as onchange) to finish before proceeding

When a group of interconnected input fields have an onchange event, the values in some fields are updated correctly while others are not due to interference from the onchange event. Once the onchange event is triggered on a field, it initiates a process t ...

What is the method to retrieve the local filepath from a file input using Javascript in Internet Explorer 9?

I'm experiencing some issues with the image-preview function on IE9, similar to the example photo shown. This method is not functioning properly and throwing an error in IE9, while it works perfectly fine in IE6-8. I am looking for a way to retrieve ...

The Vue.js Vuetify.js error message is saying "A mystery custom element: <v-list-item>, <v-list-item-title> - Have you properly registered the component?"

I followed the instructions from Vuetify Data Iterator Filter section I am able to use various Vuetify components like v-btn, v-card, v-data-table, v-data-iterator, and more. However, I encountered errors only with <v-list-item> and <v-list-item ...

Dealing with unresolved promises in async/await functions

What is the best approach for handling unresolved promises? For instance: class Utils { static async thisFunctionOnlyResolvesWhenPassed2AndNeverRejects(number: number) { return new Promise((resolve, reject) => { if(number === 2 ...