Calculate time difference | strings [duplicate] - javascript

This question already has answers here:
JavaScript - Get minutes between two dates
(12 answers)
How can I compare two time strings in the format HH:MM:SS?
(16 answers)
Closed 6 years ago.
I want to display the amount of minutes between the scheduled time and expected time.
This is not to compare, this is to calculate how many minutes there are in different times in both scheduled and expected.
Since both times are displayed as a string, do I need to convert string to a number and then do a comparison?
All I want to return is the difference in time as a number.
Here is my object:
{
station: "Macclesfield",
scheduled: "15:41",
expected: "15:50",
platform: "1"
}

var data = {
station: "Macclesfield",
scheduled: "15:41",
expected: "15:50",
platform: "1"
}
function getTimeDifference(scheduled, expected) {
scheduled = scheduled.split(':'); //get array [hours, minutes]
expected = expected.split(':');
var hours = expected[0] - scheduled[0]; //difference in hours
var minutes = expected[1] - scheduled[1]; //difference in minutes
if (minutes < 0) { //if minutes are negative we know it wasn't a full hour so..
hours--; //subtract an hour
minutes += 60; //add 60 minutes
} //now we're ok
if (hours) //if hours has a value
return hours + ':' + minutes;
return minutes; //hours is 0 so we only need the minutes
}
console.log(getTimeDifference(data.scheduled, data.expected));
data.expected = "16:00";
console.log(getTimeDifference(data.scheduled, data.expected));
data.expected = "17:00";
console.log(getTimeDifference(data.scheduled, data.expected));

var obj = { scheduled: "15:41", expected: "15:50" }
var milliSeconds = Date.parse(`01/01/2011 ${obj.expected}:00`) - Date.parse(`01/01/2011 ${obj.scheduled}:00`)
var minutes = milliSeconds / (1000 * 60)
var hours = milliSeconds / (1000 * 60 * 60)

Related

jquery if hours and minutes <> [duplicate]

This question already has an answer here:
The correct way to compare time in javascript? [duplicate]
(1 answer)
Closed 1 year ago.
Please, How can I set IF when time is < 21:30 ??
var dt = new Date();
if ((dt.getHours() <= 21) && (dt.getMinutes() <= 30)) { alert("check"); }
This not working when time is example 20:45
You need to check two different things.
if hours <= 20, than everything is true.
if hours == 21, than check minutes.
var dt = new Date('2021/03/18 20:45:00');
if (dt.getHours() <= 20 || (dt.getHours() == 21 && dt.getMinutes() <= 30)) {
alert("check");
}
You could always take the time and convert it to minutes in the day - 1440 (60*24) so 21:30 becomes 21 * 60 + 30 = 1,290.
We can calculate the current minute value by taking the current date time Date.now() (milliseconds since 1/1/1970) mod 86,400,000 (milliseconds in a day) * further divide this by 60,000 (milliseconds in a minute).
(Date.now() % 86_400_000) / (60_000)
It is then trivial to compare these two values
const nineFortyFivePM = 21 * 60 + 30;
const currentMinutes = (Date.now() % 86_400_000) / (60_000);
console.log(`21:45 = ${nineFortyFivePM}`);
console.log(`currentMinutes = ${currentMinutes}`);
if (currentMinutes < nineFortyFivePM)
alert('check');

How to add a zero if the number of seconds is less than 10? After converting integer to minutes and seconds [duplicate]

This is a common problem but I'm not sure how to solve it. The code below works fine.
var mind = time % (60 * 60);
var minutes = Math.floor(mind / 60);
var secd = mind % 60;
var seconds = Math.ceil(secd);
However, when I get to 1 hour or 3600 seconds it returns 0 minutes and 0 seconds. How can I avoid this so it returns all the minutes?
To get the number of full minutes, divide the number of total seconds by 60 (60 seconds/minute):
const minutes = Math.floor(time / 60);
And to get the remaining seconds, multiply the full minutes with 60 and subtract from the total seconds:
const seconds = time - minutes * 60;
Now if you also want to get the full hours too, divide the number of total seconds by 3600 (60 minutes/hour · 60 seconds/minute) first, then calculate the remaining seconds:
const hours = Math.floor(time / 3600);
time = time - hours * 3600;
Then you calculate the full minutes and remaining seconds.
Bonus:
Use the following code to pretty-print the time (suggested by Dru):
function str_pad_left(string, pad, length) {
return (new Array(length + 1).join(pad) + string).slice(-length);
}
const finalTime = str_pad_left(minutes, '0', 2) + ':' + str_pad_left(seconds, '0', 2);
Another fancy solution:
function fancyTimeFormat(duration) {
// Hours, minutes and seconds
const hrs = ~~(duration / 3600);
const mins = ~~((duration % 3600) / 60);
const secs = ~~duration % 60;
// Output like "1:01" or "4:03:59" or "123:03:59"
let ret = "";
if (hrs > 0) {
ret += "" + hrs + ":" + (mins < 10 ? "0" : "");
}
ret += "" + mins + ":" + (secs < 10 ? "0" : "");
ret += "" + secs;
return ret;
}
console.log(
fancyTimeFormat(1),
fancyTimeFormat(10),
fancyTimeFormat(100),
fancyTimeFormat(1000),
fancyTimeFormat(10000),
);
~~ is a shorthand for Math.floor, see this link for more info
For people dropping in hoping for a quick simple and thus short solution to format seconds into M:SS :
function fmtMSS(s){return(s-(s%=60))/60+(9<s?':':':0')+s}
done..
The function accepts either a Number (preferred) or a String (2 conversion 'penalties' which you can halve by prepending + in the function call's argument for s as in: fmtMSS(+strSeconds)), representing positive integer seconds s as argument.
Examples:
fmtMSS( 0 ); // 0:00
fmtMSS( '8'); // 0:08
fmtMSS( 9 ); // 0:09
fmtMSS( '10'); // 0:10
fmtMSS( 59 ); // 0:59
fmtMSS( +'60'); // 1:00
fmtMSS( 69 ); // 1:09
fmtMSS( 3599 ); // 59:59
fmtMSS('3600'); // 60:00
fmtMSS('3661'); // 61:01
fmtMSS( 7425 ); // 123:45
Breakdown:
function fmtMSS(s){ // accepts seconds as Number or String. Returns m:ss
return( s - // take value s and subtract (will try to convert String to Number)
( s %= 60 ) // the new value of s, now holding the remainder of s divided by 60
// (will also try to convert String to Number)
) / 60 + ( // and divide the resulting Number by 60
// (can never result in a fractional value = no need for rounding)
// to which we concatenate a String (converts the Number to String)
// who's reference is chosen by the conditional operator:
9 < s // if seconds is larger than 9
? ':' // then we don't need to prepend a zero
: ':0' // else we do need to prepend a zero
) + s ; // and we add Number s to the string (converting it to String as well)
}
Note: Negative range could be added by prepending (0>s?(s=-s,'-'):'')+ to the return expression (actually, (0>s?(s=-s,'-'):0)+ would work as well).
2020 UPDATE
Using basic math and simple javascript this can be done in just a few lines of code.
EXAMPLE - Convert 7735 seconds to HH:MM:SS.
MATH:
Calculations use:
Math.floor() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor
The Math.floor() function returns the largest integer less than or equal to a given number.
% arithmetic operator (Remainder) - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder
The remainder operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.
Check out code below. Seconds are divided by 3600 to get number of hours and a remainder, which is used to calculate number of minutes and seconds.
HOURS => 7735 / 3600 = 2 remainder 535
MINUTES => 535 / 60 = 8 remainder 55
SECONDS => 55
LEADING ZEROS:
Many answers here use complicated methods to show number of hours, minutes and seconds in a proper way with leading zero - 45, 04 etc. This can be done using padStart(). This works for strings so the number must be converted to string using toString().
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
The padStart() method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string.
CODE:
function secondsToTime(e){
const h = Math.floor(e / 3600).toString().padStart(2,'0'),
m = Math.floor(e % 3600 / 60).toString().padStart(2,'0'),
s = Math.floor(e % 60).toString().padStart(2,'0');
return h + ':' + m + ':' + s;
//return `${h}:${m}:${s}`;
}
console.log(secondsToTime(7735)); // 02:08:55
/*
secondsToTime(SECONDS) // HH:MM:SS
secondsToTime(8) // 00:00:08
secondsToTime(68) // 00:01:08
secondsToTime(1768) // 00:29:28
secondsToTime(3600) // 01:00:00
secondsToTime(5296) // 01:28:16
secondsToTime(7735) // 02:08:55
secondsToTime(45296) // 12:34:56
secondsToTime(145296) // 40:21:36
secondsToTime(1145296) // 318:08:16
*/
2019 best variant
Format hh:mm:ss
console.log(display(60 * 60 * 2.5 + 25)) // 2.5 hours + 25 seconds
function display (seconds) {
const format = val => `0${Math.floor(val)}`.slice(-2)
const hours = seconds / 3600
const minutes = (seconds % 3600) / 60
return [hours, minutes, seconds % 60].map(format).join(':')
}
You can also use native Date object:
var date = new Date(null);
date.setSeconds(timeInSeconds);
// retrieve time ignoring the browser timezone - returns hh:mm:ss
var utc = date.toUTCString();
// negative start index in substr does not work in IE 8 and earlier
var time = utc.substr(utc.indexOf(':') - 2, 8)
// retrieve each value individually - returns h:m:s
var time = date.getUTCHours() + ':' + date.getUTCMinutes() + ':' + date.getUTCSeconds();
// does not work in IE8 and below - returns hh:mm:ss
var time = date.toISOString().substr(11, 8);
// not recommended - only if seconds number includes timezone difference
var time = date.toTimeString().substr(0, 8);
Of course this solution works only for timeInSeconds less than 24 hours ;)
function secondsToMinutes(time){
return Math.floor(time / 60)+':'+Math.floor(time % 60);
}
To add leading zeros, I would just do:
const secondsToMinSecPadded = time => {
const minutes = "0" + Math.floor(time / 60);
const seconds = "0" + (time - minutes * 60);
return minutes.substr(-2) + ":" + seconds.substr(-2);
};
console.log(secondsToMinSecPadded(241));
Nice and short
Moment.js
If you are using Moment.js then you can use there built in Duration object
const duration = moment.duration(4825, 'seconds');
const h = duration.hours(); // 1
const m = duration.minutes(); // 20
const s = duration.seconds(); // 25
Clean one liner using ES6
const secondsToMinutes = seconds => Math.floor(seconds / 60) + ':' + ('0' + Math.floor(seconds % 60)).slice(-2);
The most concise method I found can be done using in just one line:
let timeString = `${timeInSeconds/60|0}:${timeInSeconds%60}`
Explanation
`${...}`Template literals. Allows for expressions to be converted into a string from within the string itself.Note: Incompatible with IE.
timeInSeconds/60|0Takes the seconds and converts in into minutes (/60). This gives a rational number. From here it is truncated using the bitwise OR (|0)
timeInSeconds%60Remainder (modulo). Gives the remainder of the variable divided by 60.
Hours
This method can be expanded to include hours like this:
let timeString = `${timeInSeconds/60/60|0}:${timeInSeconds/60%60|0}:${timeInSeconds%60}`
Repeating this process, you can even include days.
A one liner (doesnt work with hours):
function sectostr(time) {
return ~~(time / 60) + ":" + (time % 60 < 10 ? "0" : "") + time % 60;
}
Seconds to h:mm:ss
var hours = Math.floor(time / 3600);
time -= hours * 3600;
var minutes = Math.floor(time / 60);
time -= minutes * 60;
var seconds = parseInt(time % 60, 10);
console.log(hours + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds));
The Following function will help you to get Days , Hours , Minutes , seconds
toDDHHMMSS(inputSeconds){
const Days = Math.floor( inputSeconds / (60 * 60 * 24) );
const Hour = Math.floor((inputSeconds % (60 * 60 * 24)) / (60 * 60));
const Minutes = Math.floor(((inputSeconds % (60 * 60 * 24)) % (60 * 60)) / 60 );
const Seconds = Math.floor(((inputSeconds % (60 * 60 * 24)) % (60 * 60)) % 60 );
let ddhhmmss = '';
if (Days > 0){
ddhhmmss += Days + ' Day ';
}
if (Hour > 0){
ddhhmmss += Hour + ' Hour ';
}
if (Minutes > 0){
ddhhmmss += Minutes + ' Minutes ';
}
if (Seconds > 0){
ddhhmmss += Seconds + ' Seconds ';
}
return ddhhmmss;
}
alert( toDDHHMMSS(2000));
After all this, yet another simple solution:
const time = new Date(null);
time.setSeconds(7530);
console.log(time.getHours(), time.getMinutes(), time.getSeconds());
Another but much more elegant solution for this is as follows:
/**
* Convert number secs to display time
*
* 65 input becomes 01:05.
*
* #param Number inputSeconds Seconds input.
*/
export const toMMSS = inputSeconds => {
const secs = parseInt( inputSeconds, 10 );
let minutes = Math.floor( secs / 60 );
let seconds = secs - minutes * 60;
if ( 10 > minutes ) {
minutes = '0' + minutes;
}
if ( 10 > seconds ) {
seconds = '0' + seconds;
}
// Return display.
return minutes + ':' + seconds;
};
function formatSeconds(s: number) {
let minutes = ~~(s / 60);
let seconds = ~~(s % 60);
return minutes + ':' + seconds;
}
For adding zeros I really don't see the need to have a full other function where you can simply use for example
var mins=Math.floor(StrTime/60);
var secs=StrTime-mins * 60;
var hrs=Math.floor(StrTime / 3600);
RoundTime.innerHTML=(hrs>9?hrs:"0"+hrs) + ":" + (mins>9?mins:"0"+mins) + ":" + (secs>9?secs:"0"+secs);
Its why we have conditional statements in the first place.
(condition?if true:if false) so if example seconds is more than 9 than just show seconds else add a string 0 before it.
var seconds = 60;
var measuredTime = new Date(null);
measuredTime.setSeconds(seconds); // specify value of SECONDS
var Time = measuredTime.toISOString().substr(11, 8);
document.getElementById("id1").value = Time;
<div class="form-group">
<label for="course" class="col-md-4">Time</label>
<div class="col-md-8">
<input type="text" class="form-control" id="id1" name="field">Min
</div>
</div>
Try this:
Converting Second to HOURS, MIN and SEC.
function convertTime(sec) {
var hours = Math.floor(sec/3600);
(hours >= 1) ? sec = sec - (hours*3600) : hours = '00';
var min = Math.floor(sec/60);
(min >= 1) ? sec = sec - (min*60) : min = '00';
(sec < 1) ? sec='00' : void 0;
(min.toString().length == 1) ? min = '0'+min : void 0;
(sec.toString().length == 1) ? sec = '0'+sec : void 0;
return hours+':'+min+':'+sec;
}
1 - Get rest of division using %. Now you have the seconds that don't complete a minute
2 - Subtract the seconds obtained in step 1 from the total. Now you have the minutes
For example, let's assume you have 700 seconds:
seconds = 700%60); //40 seconds
minutes = (700 - (700%60))/60; //11
//11:40
I was thinking of a faster way to get this done and this is what i came up with
var sec = parseInt(time);
var min=0;
while(sec>59){ sec-=60; min++;}
If we want to convert "time" to minutes and seconds, for example:
// time = 75,3 sec
var sec = parseInt(time); //sec = 75
var min=0;
while(sec>59){ sec-=60; min++;} //sec = 15; min = 1
Put my two cents in :
function convertSecondsToMinutesAndSeconds(seconds){
var minutes;
var seconds;
minutes = Math.floor(seconds/60);
seconds = seconds%60;
return [minutes, seconds];
}
So this :
var minutesAndSeconds = convertSecondsToMinutesAndSeconds(101);
Will have the following output :
[1,41];
Then you can print it like so :
console.log('TIME : ' + minutesSeconds[0] + ' minutes, ' + minutesSeconds[1] + ' seconds');
//TIME : 1 minutes, 41 seconds
export function TrainingTime(props) {
const {train_time } = props;
const hours = Math.floor(train_time/3600);
const minutes = Math.floor((train_time-hours * 3600) / 60);
const seconds = Math.floor((train_time%60));
return `${hours} hrs ${minutes} min ${seconds} sec`;
}
Day.js
If you use day.js, try this.
const dayjs = require('dayjs')
const duration = require('dayjs/plugin/duration')
dayjs.extend(duration)
const time = dayjs.duration(100, 'seconds')
time.seconds() // 40
time.minutes() // 1
time.format('mm:ss') // 01:40
I prefer thinking of Millisecond as its own unit, rather than as a subunit of something else. In that sense, it will have values of 0-999, so you're going to want to Pad three instead of two like I have seen with other answers. Here is an implementation:
function format(n) {
let mil_s = String(n % 1000).padStart(3, '0');
n = Math.trunc(n / 1000);
let sec_s = String(n % 60).padStart(2, '0');
n = Math.trunc(n / 60);
return String(n) + ' m ' + sec_s + ' s ' + mil_s + ' ms';
}
console.log(format(241));
https://developer.mozilla.org/Web/JavaScript/Reference/Global_Objects/String/padStart
Here's an ES6 version of the seconds to minutes and seconds conversion, with padding (00:00 format). It only accepts integer values for seconds and ~~(x) is the shorthand floor operation.
const padTime = n => ("" + n).padStart(2, 0);
const secondsToMinSec = time =>
`${padTime(~~(time / 60))}:${padTime(time - ~~(time / 60) * 60)}`
;
for (let i = 0; i < 10; i++) {
const seconds = ~~(Math.random() * 300);
console.log(seconds, secondsToMinSec(seconds));
}
if you need to work with the result easily later this is what I use:
function seconds2hms(seconds, milliseconds) {
if(milliseconds) {
seconds = Math.floor(seconds/1000);
}
return {h:~~(seconds / 3600),m:~~((seconds % 3600) / 60),s:~~seconds % 60}
}
(used Vishal's code)
strftime.js (strftime github) is one of the best time formatting libraries. It's extremely light - 30KB - and effective. Using it you can convert seconds into time easily in one line of code, relying mostly on the native Date class.
When creating a new Date, each optional argument is positional as follows:
new Date(year, month, day, hours, minutes, seconds, milliseconds);
So if you initialize a new Date with all arguments as zero up to the seconds, you'll get:
var seconds = 150;
var date = new Date(0,0,0,0,0,seconds);
=> Sun Dec 31 1899 00:02:30 GMT-0500 (EST)
You can see that 150 seconds is 2-minutes and 30-seconds, as seen in the date created. Then using an strftime format ("%M:%S" for "MM:SS"), it will output your minutes' string.
var mm_ss_str = strftime("%M:%S", date);
=> "02:30"
In one line, it would look like:
var mm_ss_str = strftime('%M:%S', new Date(0,0,0,0,0,seconds));
=> "02:30"
Plus this would allow you to interchangeable support HH:MM:SS and MM:SS based on the number of seconds. For example:
# Less than an Hour (seconds < 3600)
var seconds = 2435;
strftime((seconds >= 3600 ? '%H:%M:%S' : '%M:%S'), new Date(0,0,0,0,0,seconds));
=> "40:35"
# More than an Hour (seconds >= 3600)
var seconds = 10050;
strftime((seconds >= 3600 ? '%H:%M:%S' : '%M:%S'), new Date(0,0,0,0,0,seconds));
=> "02:47:30"
And of course, you can simply pass whatever format you want to strftime if you want the time string to be more or less semantic.
var format = 'Honey, you said you\'d be read in %S seconds %M minutes ago!';
strftime(format, new Date(0,0,0,0,0,1210));
=> "Honey, you said you'd be read in 10 seconds 20 minutes ago!"
You've done enough code to track minutes and seconds portions of time.
What you could do is add the hours factor in:
var hrd = time % (60 * 60 * 60);
var hours = Math.floor(hrd / 60);
var mind = hrd % 60;
var minutes = Math.floor(mind / 60);
var secd = mind % 60;
var seconds = Math.ceil(secd);
var moreminutes = minutes + hours * 60

How do i check given duration times (00:20:40,1:20:40,00:00:10) is <20sec, >1hour and <10 seconds [duplicate]

This question already has answers here:
How can I convert a HH:mm:ss string to a JavaScript Date object?
(3 answers)
Closed 4 years ago.
I am having a field called Duration it contains time like 00:20:40.How do i check given duration times (00:20:40,1:20:40,00:00:10) is <20sec, >1hour and <10 seconds .I tried the following but didn't work.
var time = new Date('00:10:40');
time.getMinutes();
Output will look like:
The given time is <20 minute.Hence i need to check like this
if(<20 minutes){...}
You have to create Date Object with Date to use it.
var d = new Date("1970-01-01 20:18:02");
document.write(d.getMinutes());
You can do the following:
var time = "00:20:40".split(":");
var minutes = time[1];
The given string "00:20:40" is not a valid date string and cannot be passed to new Date() as an argument. In this case, you can use the above solution which will split the string and give you an array consisting of [hh, mm, ss] and you will be able to get the minutes at time[1].
I hope it helps.
function toSeconds (duration) {
const regex = /(\d+):(\d+):(\d+)/;
const matched = duration.match(regex);
const hours = parseInt(matched[1]);
const minutes = parseInt(matched[2]);
const seconds = parseInt(matched[3]);
return (hours * 60 * 60) + (minutes * 60) + seconds;
}
function toMinutes (duration) {
const seconds = toSeconds(duration);
return seconds / 60;
}
function toHours (duration) {
const minutes = toMinutes(duration);
return minutes / 60;
}
toSeconds('00:20:40') // 1240
toMinutes('00:20:40') // 20.666666666666668
toMinutes('01:20:40') // 80.66666666666667
toHours('01:20:40') // 1.3444444444444446

convert integer seconds to equivalent three hours , minutes and seconds interger [duplicate]

This question already has answers here:
Convert seconds to HH-MM-SS with JavaScript?
(38 answers)
Closed 6 years ago.
Suppose I have an integer number as a variable. (this number can be any integer number).
Now I want to create a countdown timer based on this number on the page.
To create countDown, I am using jquery-countdownTimer plugin.
A simple usage of this plugin is like this :
$(function(){
$("#hms_timer").countdowntimer({
hours : 3‚
minutes : 10‚
seconds : 10‚
size : "lg"‚
pauseButton : "pauseBtnhms"‚
stopButton : "stopBtnhms"
});
});
As you see , it gets hours , minutes and seconds in 3 separate numbers.
Now my question is how can I convert an integer number to Equivalent hours , minutes and seconds in simplest way?
function getTime(s) {
var secs = parseInt(s, 10); // don't forget the second param
var hours = Math.floor(secs / 3600);
var minutes = Math.floor((secs - (hours * 3600)) / 60);
var seconds = secs - (hours * 3600) - (minutes * 60);
return {
hours: hours,
minutes: minutes,
seconds: seconds
};
}
var time = getTime("3792");
alert("Hours: " + time.hours + "\nMinutes: " + time.minutes + "\nSeconds: " + time.seconds);

Countdown of between two datetime using jquery [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have two dates as like one is 2016-02-23 15:12:12 and another one is 2016-02-29 18:16:42 then how to display hh:mm:ss countdown to subtract this two dates using jquery
Please help Thanks in advance
You try like this
var timer;
var compareDate = new Date();
compareDate.setDate(compareDate.getDate() + 7); //just for this demo today + 7 days
timer = setInterval(function() {
timeBetweenDates(compareDate);
}, 1000);
function timeBetweenDates(toDate) {
var dateEntered = toDate;
var now = new Date();
var difference = dateEntered.getTime() - now.getTime();
if (difference <= 0) {
// Timer done
clearInterval(timer);
} else {
var seconds = Math.floor(difference / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
$("#days").text(days);
$("#hours").text(hours);
$("#minutes").text(minutes);
$("#seconds").text(seconds);
}
}
or
you can use countDownjs
http://countdownjs.org/demo.html
Note : better to use 3rd party library because someone wrote code for this you better plug it and start using do not waste time when you have some resource for that.
There are two problems you're looking to solve here.
How do you get the difference between two Date objects in javascript
How do you display that difference in hours, minutes, seconds
Get difference between two Date objects in javascript
First, you need to get the Unix timestamp of each Date object, which is the total number of elapsed seconds from the epoch. Then you can subtract these two values to get the total difference in seconds. To do this we rely on Date's getTime() method, which in javascript returns the number of milliseconds since the epoch.
var start = new Date('2016-02-12 15:12:12');
var end = new Date('2016-02-22 18:16:42');
/* This gives us an integer value of the difference in seconds */
var diff = Math.round((end.getTime() - start.getTime()) / 1000);
Display the difference in hours, minutes, and seconds
The second part requires doing some basic clock arithmetic to get the number of hours, minutes, and seconds from the diff value.
Since there are 3600 seconds in an hour, the total number of hours in this value are Math.floor(diff / 3600). Since there are 60 seconds in every minute, the total number of minutes in this value are Math.floor((diff - (hours * 3600)) / 60), where diff is less the number of hours multiplied by 3600. Subsequently the total number of seconds in this value are just the remainder of the diff, less hours and minutes, from the quotient 60 ((diff - hours * 3600) - (minutes * 60) % 60), which we get from the modulus operator.
function getClock(seconds) {
var hours = Math.floor(diff / 3600);
diff -= hours * 3600
var minutes = Math.floor(diff / 60);
diff -= minutes * 60;
var seconds = diff % 60;
return hours + ":" + minutes + ":" + seconds;
}
Putting it all together
If you want to display countdown clocks like this there are some nifty jquery plugins jQuery Countdown which make this process a lot easier. But I felt it important to explain the details behind the programming, none-the-less.
var date1="2016-02-12 15:12:12";
var date2="2016-02-22 18:16:42";
var d1= date1.split(" ");
d1=d1[1];
var d2= date2.split(" ");
d2=d2[1];
d1=d1.split(":");
d2=d2.split(":");
var hours=d2[0]-d1[0];
var mins=d2[1]-d1[1];
var sec=d2[2]-d1[2];
var countdown=hours+":"+mins+":"+sec;
console.log(countdown);
this will give you time remaining.there are some libs for time countdown.you can use use them

Categories