Posted on September 1st, 2007
14243 views
First off, this is my first tutorial I've ever written and it's not my native language so there might be several grammar failures. But I hope you understand what I want to tell you with this small tutorial.
The tutorial is not about how to calculate differences from dates, it's how to calculate differences from times. This is the code I want to explain: The result is not in minutes. For example 0.25 h would be 15 minutes.
So let's see what we've got here... the first thing is we need to define the 2 times from what we want the difference and we need them in a specific format. I just used the date function for this so we can use every time format. For this I just used an array with 2 values. The first value($hour[0]) is the start and the second one($hour[1]) is the end. The next part looks a bit complicated but it's actually very simple. Let's cut it into pieces! the first phrase (int)$hours[0])*60 is just taking the hours without the minutes and calculates the minut out of it. From the first value 13.3 it would be 780 minutes because we have 13 hours * 60 minutes are 780 minutes. The next part ($hours[0]-((int)$hours[0]))*100) is cutting off the hours from the minutes. From 13.30 it's now becoming 0.3. But we don't have 0.3 minutes so we have to multiplicate it with 100 to become 30 minutes. That's actually it! The if clause is just if you have two times, but on different dates. For example 22.30 and 00.23. So the end time would be smaller than the start date. That's why we add 24 hours to the end date if the end date is smaller than the start date. This only works if you know that your time differences are not more than one day! In the last part we print it out with the function sprintf. This way we have a formatted output. it's always 0.00. The small calculation behind is just subtracting the start date from the end date and dann dividing it with 60 because we have minutes, but we want hours again. Well that's basically it. I hope you understood my poor english. |