I have two strings like
var x = "22:10";
var y = "23:15";
How can i calculate using javascript the time is remaining to x get into y?
in this case would be
var final = "01:05"
Thanks!
I have two strings like
var x = "22:10";
var y = "23:15";
How can i calculate using javascript the time is remaining to x get into y?
in this case would be
var final = "01:05"
Thanks!
@Man of Snow solution is simple and I think it works well, but if you will need more complex example for working with dates you can review my code:
var x = "22:10";
var y = "23:15";
function createDate(v) {
var date = new Date(),
va = v.split(':');
date.setHours(va[0]);
date.setMinutes(va[1]);
return date;
}
function getDiff(x, y) {
var date1 = createDate(x),
date2 = createDate(y);
var result = new Date();
result.setTime(date2.getTime() - date1.getTime());
var hours = result.getUTCHours().toString(),
minutes = result.getUTCMinutes().toString();
if (hours.length == 1) {
hours = '0' + hours;
}
if (minutes.length == 1) {
minutes = '0' + minutes;
}
return hours + ':' + minutes;
}
var diff = getDiff(x, y);
alert(diff);
Here's the code!
var x = "22:10";
var y = "23:15";
var xTotal = parseInt(x.split(':')[0] * 60) + parseInt(x.split(':')[1]);
var yTotal = parseInt(y.split(':')[0] * 60) + parseInt(y.split(':')[1]);
var total = yTotal - xTotal;
var minutes = Math.floor(total / 60);
var seconds = total - minutes * 60;
if(seconds.toString().length == 1)
{
seconds = seconds.toString();
seconds = '0' + seconds;
}
var final = minutes.toString() + ':' + seconds.toString();
console.log(final);
which logs 1:05 (as you can see will also work with minutes).
I'm glad you asked, Ben. Well, it converts the first and second part around the colon to seconds (minutes * 40), of course parseInt
, because they're Strings! Anyways, it now divides that number's rounded state (Math.floor()
for you programmers at home) by 60 to get the amount of minutes. And you know what it does then, Ben?
(Ben: Nope, but I wish it did what I thought.)
I'm glad you say so, Ben! Well, here's what it does then: It actually takes that total number of seconds and subtracts it by the number of minutes * 60, and what does it do now? Well, I'll tell you, Ben! It actually converts it into a string! Minutes, a colon, then seconds! How cool's that?
(Ben: Great, we'll be in touch. Next?)
It's right over here, Ben! (which alerts instead of logs)
...who's Ben???
You can use
function padding(str, len, char) {
return (Array(len).join(char)+str).substr(-len);
}
var x = "22:10",
y = "23:15",
day = "Sun Jan 05 2014 ", // or whatever
final = new Date(new Date(day+y)-new Date(day+x));
final = padding(final.getUTCHours(), 2, 0) + ':' + padding(final.getUTCMinutes(), 2, 0);