数学计算预订期

时间:2016-02-04 22:00:38

标签: javascript php algorithm geometry

我需要帮助在我的图表上绘制时间。我的html页面上有一个水平横跨24个框的网格。每个方框代表一个小时,在我的电子表格中定义宽度为28px。第一个框从上午12点开始,然后一直到晚上11点(24小时)。

我现在需要做的是在网格上绘制我的项目,唯一的问题是我无法弄清楚数学计算出左侧位置应该从哪里开始以及应该有多宽。我的代码中的左侧位置基于百分比,0%是12AM的开始。宽度以像素为单位。有谁可以告诉我的方式?

所以我假设我有以下项目,左边位置(%)和宽度(px)是什么。我只需要公式,因为我可以解决如何编码并将其注入我的网格

Name, StartTime, EndTime
Item 1, 9:55, 14:55
Item 2, 16:00, 17:45
Item 2, 18:10, 19:55

1 个答案:

答案 0 :(得分:0)

您有n = 24个方框,宽度为w = 28个px。时间可由h小时和m分钟表示。

基本上你只想找出每个盒子的开始和结束,然后你可以将它转换为像素宽度,并将 转换为百分比。

  1. h + m/60会给你分数小时。乘以宽度以获取时间的像素位置:(h + m/60)*w。 (快速健全性检查:1:30应该是1个半宽,或42个像素。)

  2. 两次都这样做,现在你有start_pxend_px。这样可以计算width = end_px - start_px

  3. 现在您可以将其转换为百分比:width_percent = width / total_width * 100 = width / (w * n) * 100

  4. 所以你的最终公式应该是这样的:

    start_px = (start_h + start_m/60)*w
    end_px = (end_h + end_m/60)*w
    width_percent = (end_px - start_px) / (w * n) * 100
    

    编辑:这是一个快速而肮脏的Python 2脚本(正如我所掌握的那样)来运行一些示例。

    def find_width(start_h, start_m, end_h, end_m, n, w):
        start_px = (start_h + start_m/60.)*w
        end_px = (end_h + end_m/60.)*w
        width_percent = (end_px - start_px)/(w*n)*100
        print "%d:%02d-%d:%02d Spans from %dpx to %dpx, or %.2f%%"%(start_h, start_m, end_h, end_m, start_px, end_px, width_percent)
    
    n = 24 # 24 hours
    w = 10 # width of 10, easier to check math
    
    # entire day - should be 240 px or 100%
    find_width(0,0, 24,0, n,w)
    
    # half day - should be 50%
    find_width(0,0, 12,0, n,w)
    
    # try starting from not-zero
    find_width(4,0, 16,0, n,w)
    find_width(4,30, 5,30, n,w)
    
    # try non-zero minutes
    find_width(4,30, 16,30, n,w)
    
    # try less than an hour
    find_width(4,30, 5,00, n,w)
    find_width(4,30, 4,45, n,w)
    

    输出:

    0:00-24:00 Spans from 0px to 240px, or 100.00%
    0:00-12:00 Spans from 0px to 120px, or 50.00%
    4:00-16:00 Spans from 40px to 160px, or 50.00%
    4:30-5:30 Spans from 45px to 55px, or 4.17%
    4:30-16:30 Spans from 45px to 165px, or 50.00%
    4:30-5:00 Spans from 45px to 50px, or 2.08%
    4:30-4:45 Spans from 45px to 47px, or 1.04%