找到最近的时间跨度

问题描述 投票:0回答:1

我有一个要求,我说2个参数一个bucketDelta和一个开始时间,我需要计算bucketDelta步骤中最接近的时间间隔小于给定时间。 (听起来很复杂?这是一个例子)

说bucketDelta 15分钟,我的时间是9月13日晚上7:05 - 返回9月13日晚上7:00 15分钟,我的时间是9月13日晚上7:17 - 返回9月13日晚上7:15 15分钟,我的时间是9月13日7:35 PM - 9月13日晚7:30返回......

30分钟,我的时间是9月13日下午7:05 - 返回9月9日晚上7:00 30分钟,我的时间是9月13日晚上7:17 - 返回9月13日晚上7:00 30分钟,我的时间是9月13日:下午35点 - 9月13日晚7:30返回

...

60分钟,我的时间是9月13日晚上7:05 - 返回9月9日晚上7:00 60分钟,我的时间是9月13日晚上7:35 - 返回9月9日晚上7:00 60分钟,我的时间是9月13日:下午55点 - 9月13日晚7点返回

24小时和我的时间是9月13日下午7:05 - 返回13月9日12:00 AM 24小时,我的时间是9月13日9:05 PM - 返回13 Sep 12:00 AM ..

这是我对此的逻辑,但我对一百万个Ifs不太满意。有一个更好的方法吗 ?

            if (bucketDelta == TimeSpan.FromSeconds(900)) {
            if (bucketStop.Minute > 0 && bucketStop.Minute < 15)
            {
                minute = bucketStop.Minute;
            }
            else if (bucketStop.Minute > 15 && bucketStop.Minute < 30)
            {
                minute = bucketStop.Minute - 15;
            }
            else if (bucketStop.Minute > 30 && bucketStop.Minute < 45)
            {
                minute = bucketStop.Minute - 30;
            }
            else if (bucketStop.Minute > 45 && bucketStop.Minute < 60)
            {
                minute = bucketStop.Minute - 45;
            }
        }else if(bucketDelta == TimeSpan.FromSeconds(1800)) {
            if (bucketStop.Minute > 0 && bucketStop.Minute < 30)
            {
                minute = bucketStop.Minute;
            }
            else if (bucketStop.Minute > 30 && bucketStop.Minute < 60)
            {
                minute = bucketStop.Minute - 30;
            }
        } else if(bucketDelta == TimeSpan.FromSeconds(3600))
        {
            if (bucketStop.Minute > 0 && bucketStop.Minute < 60)
            {
                minute = bucketStop.Minute;
            }
        }
        else if (bucketDelta == TimeSpan.FromSeconds(86400))
        {
            if (bucketStop.Hour > 0 && bucketStop.Hour < 24)
            {
                minute = (bucketStop.Hour * 60);
            }
        }
        bucketStop = bucketStop.AddMinutes(-1 * minute);
algorithm date datetime openstack
1个回答
1
投票

将两者转换为标准单位的整数倍,将绝对时间除以存储桶的长度,使用floor获取整数,乘以存储桶的长度,然后转换回来。根据您的语言,floor可能是类型系统隐式的或显式的。

例如,在Java中,您的计算可能类似于以下内容(未经测试):

long intervals = originalInstant.toEpochMilli() / bucketInMilliseconds;
Instant answer = Instant.fromEpochMilli( bucketInMilliseconds * intervals );
© www.soinside.com 2019 - 2024. All rights reserved.