Difference Between 2 Timestamps using javascript without using moment.js - javascript

I have 2 timestamps
var startTimestamp = 1488021704531;
var endTimestamp = 1488022516572;
I need the difference between these timestamps in hours and minutes using javascript but without using moment.js.
Means the output should in hours and minutes like for ex:(02h 13min).

Do provide some more context or in depth information of the solution you have up to now. That said, I understand the need/question of your second part "hours/minutes/seconds"; below is some context on that, or read up on it at milliseconds to time in javascript.
That being said,
You could just either try subtracting, as in end - start.. as in following code example.
var startTimestamp = 1488021704531;
var endTimestamp = 1488022516572;
document.write(endTimestamp - startTimestamp + '<br/>');
This will output 812041 - which are the milliseconds.
If you want to convert those milliseconds to the known format of hh:mm:ss.ms you can try the following code by example - also 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;
}
Or read other solutions in this question: milliseconds to time in javascript

Related

How can I convert total nanoseconds to string in format HH:MM:SS:ms:ns in JavaScript and node?

I am getting back a time in total nanoseconds from an api. I need to be able to print out a time in the format HH:MM:SS:ms:ns. An example output would be "12:34:56.123456789".
JavaScript Date object only supports for the millisecond so what would be the best way to do this?
Desired functionality:
Input: 38145999999999
Output: 10:36:41.999999999
Here's function which will solve your problem:
function msToTime(duration) {
var milliseconds = parseInt((duration%1000)/100)
, seconds = parseInt((duration/1000)%60)
, minutes = parseInt((duration/(1000*60))%60)
, hours = parseInt((duration/(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;
}

Best way to convert a unix timestamp to javascript date-time

I have been following Convert a Unix timestamp to time in JavaScript thread for answer but looks like single digit time (0-9) is parsed as it is. The accepted answer
// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
We get like 2:3:9 instead of 02:03:09. How to get rid of this behaviour? Also can anyone please elaborate on how to get am/pm along with time?
var formattedTime = ('0' + hours).substr(-2) + ':'
+ ('0' + minutes).substr(-2) + ':'
+ ('0' + seconds).substr(-2);
I think I will leave the am:pm bit to you. Press ctrl-shift j and play with your code in the console right here
// /*Year m-1 d h m s ms*/
unix_timestamp = Math.floor(new Date(2016,0, 1,5,5,0,0)/1000)
This might be easier to understand. I have kept it closer
// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date = new Date(unix_timestamp*1000);
// Hours part from the timestamp
var amPm = date.getHours() >= 12?'AM':'PM'
// % is modulo which is the remainder after division || will change 0 to 12
// because 0 is falsey everything else will be left as it is
var hours = ("0" + ((date.getHours() % 12)||12)).substr(-2)
// Minutes part from the timestamp
var minutes = ("0" + date.getMinutes()).substr(-2)
// Seconds part from the timestamp
var seconds = ("0" + date.getSeconds()).substr(-2)
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes+ ':' + seconds + ' '+ amPm
I think you have to get rid of the substr-part, since the value should already be correct.
Note: you need to check if the values are already above 9, because you don't need to append anything when it is above 9.
Example
var d = new Date() //Is in milliseconds
var hours = d.getHours();
var minutes = d.getMinutes();
var seconds = d.getSeconds();
console.log(hours + ":" + ((minutes < 10) ? "0" + minutes : minutes) + ":" + ((seconds < 10) ? "0" + seconds : seconds))
I want to add that these kinds of problems can be easily resolved with using a good library like moment.js

Adding AM/PM using javascript [duplicate]

This question already has answers here:
How do you display JavaScript datetime in 12 hour AM/PM format?
(31 answers)
Closed 6 years ago.
I have simple code for 12hr format time
// This function gets the current time and injects it into the DOM
function updateClock() {
// Gets the current time
var now = new Date();
// Get the hours, minutes and seconds from the current time
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
// Format hours, minutes and seconds
if (hours > 12) {
hours = hours - 12;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
// Gets the element we want to inject the clock into
var elem = document.getElementById('clock');
// Sets the elements inner HTML value to our clock data
elem.innerHTML = hours + ':' + minutes + ':' + seconds ;
}
I want to add AM/PM please help me thanks in advance
Im just beginner on javascript
After editting your own code:
// Get the hours, minutes and seconds from the current time
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var amOrPm = 'AM';
// Format hours, minutes and seconds
if (hours > 12) {
amOrPm = 'PM';
hours = hours - 12;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
// Gets the element we want to inject the clock into
var elem = document.getElementById('clock');
// Sets the elements inner HTML value to our clock data
elem.innerHTML = hours + ':' + minutes + ':' + seconds + ' ' + amOrPm;
Try this...
var ampm = hours >= 12 ? 'pm' : 'am';
then
elem.innerHTML = hours + ':' + minutes + ':' + seconds + ' ' + ampm;
I don't know if you want to code it by yourself, but there is a really really great library which handles everything with date stuff you can imagine.
Just checkout momentjs.
It's an easy AF lib to transform dates (also in pm/am).
If you've any question :) just comment ...

How to convert milliseconds into a readable date Minutes:Seconds Format?

In JavaScript I have a variable Time in milliseconds.
I would like to know if there is any build-in function to convert efficiently this value to Minutes:Seconds format.
If not could you please point me out a utility function.
Example:
FROM
462000 milliseconds
TO
7:42
Just create a Date object and pass the milliseconds as a parameter.
var date = new Date(milliseconds);
var h = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
alert(((h * 60) + m) + ":" + s);
Thanks guys for your support, at th end I came up with this solution. I hope it can helps others.
Use:
var videoDuration = convertMillisecondsToDigitalClock(18050200).clock; // CONVERT DATE TO DIGITAL FORMAT
// CONVERT MILLISECONDS TO DIGITAL CLOCK FORMAT
function convertMillisecondsToDigitalClock(ms) {
hours = Math.floor(ms / 3600000), // 1 Hour = 36000 Milliseconds
minutes = Math.floor((ms % 3600000) / 60000), // 1 Minutes = 60000 Milliseconds
seconds = Math.floor(((ms % 360000) % 60000) / 1000) // 1 Second = 1000 Milliseconds
return {
hours : hours,
minutes : minutes,
seconds : seconds,
clock : hours + ":" + minutes + ":" + seconds
};
}
In case you already using Moment.js in your project, you can use the moment.duration function
You can use it like this
var mm = moment.duration(37250000);
console.log(mm.hours() + ':' + mm.minutes() + ':' + mm.seconds());
output: 10:20:50
See jsbin sample
It's easy to make the conversion oneself:
var t = 462000
parseInt(t / 1000 / 60) + ":" + (t / 1000 % 60)
You may like pretty-ms npm package: https://www.npmjs.com/package/pretty-ms
If that what you are searching. Headless nice formatting (time in the units that are needed as ms grow), personalisable, and cover different situations. Small and efficient for what it cover.
function msToMS(ms) {
var M = Math.floor(ms / 60000);
ms -= M * 60000;
var S = ms / 1000;
return M + ":" + S;
}

How to format $.now() with Jquery

$.now() gives me the time as miliseconds. I need to show it something like hh:mm:ss
How can I do that in Jquery?
I'd suggest just using the Javascript Date object for this purpose.
var d = new Date();
var time = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
Edit: I just came across the method below, which covers formatting issues such as the one mike-samuel mentioned and is cleaner:
var time = d.toLocaleTimeString();
function formatTimeOfDay(millisSinceEpoch) {
var secondsSinceEpoch = (millisSinceEpoch / 1000) | 0;
var secondsInDay = ((secondsSinceEpoch % 86400) + 86400) % 86400;
var seconds = secondsInDay % 60;
var minutes = ((secondsInDay / 60) | 0) % 60;
var hours = (secondsInDay / 3600) | 0;
return hours + (minutes < 10 ? ":0" : ":")
+ minutes + (seconds < 10 ? ":0" : ":")
+ seconds;
}
JSFiddle example here
http://jsfiddle.net/NHhMv/
The jquery now is nothing but
The $.now() method is a shorthand for the number returned by the expression
(new Date).getTime().
from jquery
http://api.jquery.com/jQuery.now/
and follow this link
Where can I find documentation on formatting a date in JavaScript?
new Date().toString().split(' ')[4]
or
new Date().toString().match(/\d{2}:\d{2}:\d{2}/)[0]
The toString method is basically an alias for toLocaleString in most implementations. This will return the time in the user's timezone as opposed to assuming UTC by using milliseconds if you use getTime (if you use getMilliseconds you should be OK) or toUTCString.
I'd suggest date-format jQuery plugin. Like this one or this one (I am using the former)
I'm way late to this, but thought i'd just throw this little snippet out there for the masses. This is something I use just to get a quick localized timestamp. It's pretty clean and handy.
function getStamp() {
var d = new Date();
var mm = d.getMilliseconds(), hh = d.getHours(),
MM = d.getMinutes(), ss = d.getSeconds();
return (hh < 10 ? "0" : "") + hh + (MM < 10 ? ":0" : ":") + MM + (ss < 10 ? ":0" : ":") + ss + ":" + mm;
};
jQuery doesn't have date formatting. You can roll your own with the JavaScript Date object, or you can use a library that does it for you. DateJS is one such library, which provides a rich set of formatting, parsing, and manipulation functionality. However, it hasn't been maintained in years. momentjs is under active development.

Categories