Calculating Time Difference in JavaScript Without Utilizing moment.js Library

I have two timestamps that I need to calculate the difference for.

var startTimestamp = 1488021704531;
var endTimestamp = 1488022516572;

I am looking to find the time difference between these two timestamps in hours and minutes using JavaScript, without relying on moment.js library. The desired output format should be hours and minutes like this example: (02h 13min).

Answer №1

For a more thorough explanation of the current solution, additional context or detailed information would be beneficial. Regarding the query about "hours/minutes/seconds," you can refer to the following details or explore further at milliseconds to time in javascript.

Moreover,

You may opt for subtraction as a method – such as end - start, according to the sample code below.

    var startTimestamp = 1488021704531;
    var endTimestamp = 1488022516572;
    document.write(endTimestamp - startTimestamp + '<br/>');

This will provide an output of 812041 - representing milliseconds.

If you wish to convert these milliseconds into the conventional format of hh:mm:ss.ms, you can utilize the example code below – also accessible on jsfiddle.

    var startTimestamp = 1488021704531;
    var endTimestamp = 1488022516572;
    document.write(endTimestamp - startTimestamp + '<br/>');
    document.write(millisecondsToHoursMinutesSeconds(endTimestamp - startTimestamp));
    
    document.write('<hr/>');
    
    function millisecondsToHoursMinutesSeconds(ms) {
        var milliseconds = parseInt((ms%1000)/100)
            , seconds = parseInt((ms/1000)%60)
            , minutes = parseInt((ms/(1000*60))%60)
            , hours = parseInt((ms/(1000*60*60))%24);
    
        hours = (hours < 10) ? "0" + hours : hours;
        minutes = (minutes < 10) ? "0" + minutes : minutes;
        seconds = (seconds < 10) ? "0" + seconds : seconds;
    
        return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
    }

Alternatively, peruse other solutions related to this issue in the question posted here: milliseconds to time in javascript

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

Instructions on filling the star icon with color upon clicking the button

Currently working on a project using codeIgniter where I have a form for rating products. I am facing an issue where, upon clicking the star button, only the border color changes to yellow while the center of the button remains white. Can someone please g ...

What is the best way to retrieve the content of HTML tags from a string using JavaScript or AngularJS?

I have a string with mixed content of HTML tags and text. Here is an example: var str = "<p></p><p><i>blabla</i></p><p><i><b>blaaaaaablaaaaa</b></i></p><iframe src="..." height=" ...

Fetching Data from Response Headers in Angular 4.3.3 HttpClient

(Text Editor: Visual Studio Code; TypeScript Version: 2.2.1) The main objective here is to fetch the headers of the response from a request Let's consider a scenario where we make a POST request using HttpClient within a service: import { Injec ...

Tips for setting limitations on a date picker's minimum and maximum values on an iPhone using JavaScript

I have encountered an issue with my JavaScript function that sets min and max values for the input type date. While it works perfectly on Android devices, I am facing a problem on iPhone where I am unable to restrict the calendar with the specified min and ...

Date range within a conditional statement

I have encountered this code snippet: function auto_select_param_call_time() { if (today() == date("02.01.2017") || today() == date("03.01.2017")) { auto_click_param("call_time", "Non-working day"); } else { //Do something else ...

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 ...

You cannot use a relative path when inserting an image tag in React

I am having an issue with my img tag not loading the desired image when using a relative src path in my React project. When I try: //import { ReactComponent } from '*.svg'; import React from 'react'; import firebase from "./firebas ...

Is the "Illegal invocation" error popping up when using the POST method in AJAX?

Is there a way to retrieve JSON data using the POST method in Ajax? I attempted to use the code below but encountered an error: TypeError: Illegal invocation By following the link above, I was able to access JSON-formatted data. However, please note th ...

Verify the fonts that are functioning correctly

Despite using the "dancing script" Google webfont and adding it through @font-face, font-family, I am unable to see it in the browser. I would like to know how to determine which fonts are correctly uploaded and rendering properly while viewing a website ...

Issues with IE 11: SVG Map Not Triggering Mouseenter or Mouseleave Events

I've been grappling with this issue for the past couple of days and despite trying numerous solutions, nothing seems to be working. My SVG map of the US has jQuery mouseenter and mouseleave events that function properly in browsers other than IE 11 ( ...

What is the best way to capture the output of a script from an external website using Javascript when it is returning simple text?

Recently, I decided to incorporate an external script into my project. The script in question is as follows: <script type="application/javascript" src="https://api.ipify.org"> </script> This script is designed to provide the client's IP ...

Ways to verify whether a vue instance is empty within a .vue file by utilizing the v-if directive

I am facing an issue with a for-loop in Vue that iterates through a media object using v-for to check if it contains any images. Everything is working correctly, but I want to display a div below the loop saying "There is no media" when the object is empty ...

Tips for ensuring that the headers remain fixed in both the horizontal and vertical directions while allowing the data

I have been trying to create a table with a fixed header (meaning the header must be visible both vertically and horizontally). The table should be scrollable It should have a horizontal header The vertical header should match the horizontal header When ...

Pressing the icon will trigger a top-sliding dropdown mobile menu to appear

How can I ensure my mobile dropdown menu slides in from the top when the user clicks the "header-downbar-menu" icon and slides out to the top when clicked again? Currently, the button only shows the menu but I am struggling with writing the JavaScript for ...

What is the best way to retrieve an object using callback data with jQuery?

Using jquery with a servlet to fetch data from a database. The callback function provides raw information from the database. How can I append these values to select options in jsp? Retrive_country servlet code: String sql1 = "SELECT * FROM state WHERE co ...

Correcting the reference to "/" (root) for assets after relocating the site to a subdirectory

I currently have a website located in the public_html directory, where all assets (images, css, js, etc) are referenced using /asset_folder/asset. The "/" at the beginning ensures that the browser starts from the root and navigates through the directories. ...

Experience the power of Vue Google Chart - Geochart where the chart refreshes seamlessly with data updates, although the legend seems to disappear

I have integrated vue google charts into my nuxt project. Whenever I select a different date, the data gets updated and the computed method in my geochart component correctly reads the new data. However, the legend or color bar at the bottom does not funct ...

Creating getter and setter functions for an input field model property in Angular

I need help creating getter and setter methods for an input field property. Here is my attempted code: import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', st ...

core.js encountered an issue at line 6210: TypeError - The function this.service.addDepartment does not exist

Whenever I attempt to click the 'Add' button on a web application that I'm constructing, an error pops up. core.js:6210 ERROR TypeError: this.service.addDepartment is not a function at AddEditDepComponent.addDepartment (add-edit-dep.componen ...

Looking to display a div with a unique timer?

Is there a way to display different divs with unique classes for specific durations of time? For example, I want one div to show for 2000 ms with the class 'one', then another div to show for 4000 ms with the class 'two', followed by a ...