1

假设我有一个 DateTime,例如 2010.12.27 12:33:58,并且我有一个间隔帧,假设为 2 秒,不包括最后一个边框。

所以,我有以下框架:

12:33:58(incl.)-12:34:00(excl.) - 让它成为间隔 1

12:34:00(incl.)-12:34:02(excl.) - 让它成为间隔 2

12:34:02(incl.)-12:34:04(excl.) - 让它成为间隔 3

等等。

我得到了一个随机的 DateTime 值,我必须根据上述规则关联该值。

例如。值“12:33:58”属于区间 1,“12:33:59”属于区间 1,“12:34:00”属于区间 2,依此类推。

在代码中,它应该如下所示:

var dt = DateTime.Now;
DateTime intervalStart = apply_the_algorythm(dt);

这似乎是一些带有浮点数或其他东西的简单算术运算,欢迎任何决定!

4

5 回答 5

2

如果间隔只是秒分辨率,总是除以86400,那么取今天过去的秒数,除以间隔,四舍五入为整数,再相乘,再加回到今天。像 dateinquestion.Subtract(dateinquestion.Date).TotalSeconds, ((int)seconds/interval)*interval, dateinquestion.Date.AddSeconds(...)

于 2010-12-27T08:12:35.917 回答
2

如果您希望所有间隔的范围跨越几天,可能很长,您可能希望以UNIX 秒(自 1970 年 1 月 1 日以来的秒数)表示您的DateTime值。然后你只需找出你的第一个间隔是什么时候开始的,计算从那时起经过了多少秒,然后除以 2:

int secondsSinceFirstInterval = <currDate in UNIX time>
                                 - <start of first interval in UNIX time>;
int intervalIndex = secondsSinceFirstInterval / 2;

否则你最好从午夜开始数。

于 2010-12-27T08:28:44.837 回答
1

使用TimeSpan.TotalSeconds结果除以区间的大小。

const long intervalSize = 2;
DateTime start = new DateTime(2010, 12, 27, 12, 33, 58);

TimeSpan timeSpan = DateTime.Now - start;
long intervalInSeconds = (long)timeSpan.TotalSeconds;
long intervalNumber = 1 + intervalInSeconds / intervalSize;
于 2010-12-27T08:33:11.613 回答
0
 DateTime start = new DateTime(2010, 12, 31, 12, 0, 0);
 TimeSpan frameLength = new TimeSpan(0, 0, 3);
 DateTime testTime = new DateTime(2010, 12, 31, 12, 0, 4);

 int frameIndex = 0;
 while (testTime >= start)
 {
     frameIndex++;
     start = start.Add(frameLength);
 }

 Console.WriteLine(frameIndex);
于 2010-12-27T08:20:36.770 回答
0
dates = new List<DateTime>
            {
                DateTime.Now.AddHours(-1),
                DateTime.Now.AddHours(-2),
                DateTime.Now.AddHours(-3)
            };
            dates.Sort((x, y) => DateTime.Compare(x.Date, y.Date)); 
            DateTime dateToCheck = DateTime.Now.AddMinutes(-120);
            int place = apply_the_algorythm(dateToCheck);
            Console.WriteLine(dateToCheck.ToString() + " is in interval :" +(place+1).ToString());

private int apply_the_algorythm(DateTime date)
        {
            if (dates.Count == 0)
                return -1;
            for (int i = 0; i < dates.Count; i++)
            {
                // check if the given date does not fall into any range.
                if (date < dates[0] || date > dates[dates.Count - 1])
                {
                    return -1;
                }
                else
                {
                    if (date >= dates[i]
                        && date < dates[i + 1])
                        return i;
                }
            }
            return dates.Count-1;
        }
于 2010-12-27T08:33:10.117 回答