'How to convert minutes duration to pixels for element height calculating?

I making calendar with events. Every event has start time and end time (both - dates). I want to make height of every event dynamic, that depends from event duration (difference from start and end).

Every time cell in calendar has fixed height - its 63px. Every cell duration - 15 mins. I will be very happy and thankfull to you for help



Solution 1:[1]

If I understand you correctly you have a fixed height for each 15 minutes in a day, right?

Now, if you know the start and end time, you calculate the duration as end - start. To do this, you best first convert both end and start date into minutes. I don't know how you store the time data, maybe you have the hour and minute for the start and end time or maybe something else, but you need to convert that into minutes (i.e. 6:30am gets turned into 6 * 60 + 30, which is the amount of minutes since the start of that day. Then you subtract end - start and you receive the duration of the event in minutes.

Now, to calculate the height once you have the event's duration in minutes is easy since you have a fixed height for each 15 minutes. Simply calculate (duration / 15) * fixedHeightForCell. The reasoning for this formula is that you want to see how many cells your event fills (i.e. how many 15 minutes fit into the event's duration) and then multiply that by the cell's height.

It is possibly that the above formula gives you decimal values (i.e. 300.4325 pixels), which of course doesn't make sense for pixels. This happens only when your duration is not a multiple of 15 (i.e. when your event isn't exactly as long as some amount of cells). Since decimal values don't make sense for pixels, you can simply just round those results (i.e. Math.round((duration / 15) * fixedHeightForCell).

Hope this helped.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ArtInLines