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

emailProtected pre-publish: Running `python build.py && webpack` command

i am currently using scratch-blocks through the Linux terminal I have encountered a problem which involves running the following command: python build.py && webpack [email protected] prepublish: python build.py && webpack Can anyon ...

Next-Auth: Access Session in _app.js Directly Without Using getServerSideProps

When working with React.js and React-Auth, it's important to note that calling server-side functions such as getServerSideProps can prevent you from exporting your project using next export. Below is the content of my pages/_app.js, which I structured ...

Button click does not fill in Jquery Datepicker?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <link type="text/css" href="Styles/Site.css" rel="Stylesheet" ></link > <script type="text/javascript" src= ...

Adjust background color on click using JavaScript

Could someone provide me with the JavaScript code to change the background color of a page from blue to green when a button is clicked? I have seen this feature on many websites but haven't been able to write the code myself. I am specifically lo ...

Obtain and utilize the background color to easily implement the same color in another window

For my Chrome Extension project, I am looking to retrieve the background color of the current page and then set the background color of a window to match. Can someone guide me on how to accomplish this using JavaScript (with or without jQuery), and if ne ...

Ensure that the user's credentials are accessible to all views in Node.js

I'm currently developing an Android application that utilizes Node.js web services. The initial interface requires the user to connect to a host using an IP address, login, and password in order to access all databases. I aim to save these credentials ...

A guide on implementing multiline properties in a property file for Selenium WebDriver

At the moment, I am focusing on utilizing Selenium WebDriver with code that is developed in Java. In the snippet below, I have successfully verified if the dropdown values match the UI for one dropdown. Now, I aim to extend this capability to check multip ...

Submitting data to a PHP script using AJAX and the $_POST method

I'm attempting to transfer data from my AJAX request into a PHP $_POST variable in order to update my database. HTML <form id="23" method="post"> <select name="admin" onchange="chosenadmin(23)"> <option value="rick">rick&l ...

Error: Unable to access 'createInvite' property from undefined variable

Having trouble generating an invite to one of my guild's channels. Here is the code snippet I am using: const { Client } = require("discord.js"); const client = new Client({ intents: [] }); client.on("ready", async () => { ...

What is the process for setting up Vue.js and using it in conjunction with Sails JS?

After successfully setting up the backend of my website using Sails JS, I decided to integrate Vue.js into my project. Following the installation of Vue and VueResource through npm install --save, I created an app.js file in my assets/js folder. However, ...

Execute a jQuery ajax request to a specific variable

For my Phonegap/Cordova project, I have implemented functions to handle all ajax calls in the following way: function requestData(action, id ) { var data = { user_id: localStorage.getItem('user_id') }; if( action == 'fee ...

Display a blade modal upon clicking a Vuejs button

I am working on a Laravel Vue application where I need to display user records using a datatable implemented in Vue. Above the datatable, there is a button that allows users to add new records. When a user clicks on the add button, it should trigger the ...

Discovering the initial word of a string using jQuery

I'm currently facing an issue with jQuery that I need help solving. Here's the scenario: I am creating tooltips and positioning them directly under a specific trigger using CSS. Everything is functioning correctly, but there is one problem: In ...

Modify the indentation format in CSS/JS

When the Tab key is pressed in an HTML page and the tabbed link gets highlighted, is it feasible to customize the style of that highlight? ...

Retrieve data entries from a database that have been added in the past day

I'm on a quest to figure out how I can retrieve data from the database that has been submitted within the past 24 hours. Within the table named topics, there is a column defined as start_date which utilizes timestamps. How would I go about querying t ...

What could be causing the absence of the ID definition?

Whenever I send a DELETE request, I receive an error message stating ReferenceError: id is not defined at Object.removeOne (...\services\user.js:16:38. I am unsure about the role of 'id' in \services\user.js and why it is not ...

Implementing a constant loop repeatedly in NextJs

I am seeking assistance with printing the <Icon /> 700 times on a single page. As a newcomer to NextJs, I have successfully used a for loop to console.log the icons but am unsure of how to actually display them. Any help would be greatly appreciated. ...

Step-by-step guide on permanently assigning a value in Node.js

I recently started working with node js and I am facing an issue where I need to save an id in a global variable that is required in multiple functions. However, every time the server restarts, the variable gets emptied. Is there a way to persist this va ...

Upon clicking the IconButton within the ImageListItemBar, reveal the image within a Material-UI Dialog

import * as React from 'react'; import Box from '@mui/material/Box'; import ImageList from '@mui/material/ImageList'; import ImageListItem from '@mui/material/ImageListItem'; import ImageListItemBar from '@mui/m ...

Imitate the experience of using aframe view manipulation

Is there a method to imitate user input in my Webvr application? Could I reproduce look controls in Aframe? <a-entity listener position="0 0 0" id="camera" camera="userHeight: 1.6" look-controls> ...