Reputation: 1863
In javascript application, I don't have Dates but only timings of a day in 24hrs format. How can I properly find the difference between them?
All my google search results are giving Date Time difference calculations only.
For example, If I want to find the difference between (4.15pm to 2.45 pm),
In my code I have,
var startTime = "14.45"; var endTime = "16.15";
Now var diffTime = endTime - startTime
, which should give 1.30.
To get clarity on my question, you can refer my related question SO, to understand what I am trying to achieve.
Upvotes: 1
Views: 51
Reputation: 15558
Convert your string into the smallest unit required, which is minutes in your case. Do the arithmetic to get the result in minutes. Again do arithmetic to find hours and minutes from the result. You can also add logic to check if hours is zero and change to 24 in that case. But as comments point out, bare times cannot be compared if not of the same date.
function getMinutes(timeString){
var hours = parseInt(timeString.split('.')[0], 10);
hours = hours === 0? 24 : hours;
var minutes = parseInt(timeString.split('.')[1], 10);
var totalMinutes = (hours * 60) + minutes;
return totalMinutes;
}
var startTime = "23.45";
var endTime = "0.15";
var differenceInMinutes = getMinutes(endTime) - getMinutes(startTime);
var resultString = Math.floor(differenceInMinutes/60) + "." + (differenceInMinutes%60);
Another way can be by creating dummy dates using date constructor and keeping date part as some arbitrary date (same for end and start) and do common date comparison methods.
Upvotes: 1
Reputation: 1038710
You seem to have 2 string variables in javascript. So talking about times and dates is really too early. They pretty much look like floating point numbers but if this was the case then the only arithmetic you could apply to floating point numbers is floating point arithmetic (+
, -
, *
, /
). So the first step for you would be to parse those string variables to the corresponding floating point numbers:
var startTime = '14.45';
var endTime = '16.15';
var startTimeFloat = parseFloat(startTime);
var endTimeFloat = parseFloat(endTime);
if (isNaN(startTimeFloat) || isNaN(endTimeFloat)) {
alert('Please input valid floating point numbers before being able to do any arithmetic on them');
} else {
var difference = endTimeFloat - startTimeFloat;
// Obviously here you should take into account the case where
// the start number is bigger than the end number in which case
// you would get a negative value for the difference. If you care only
// about the absolute value of the difference then you may use the
// Math.abs javascript method. Just like that:
// var difference = Math.abs(endTimeFloat - startTimeFloat);
alert(difference);
}
Upvotes: 0