一个棘手的DateTime算法问题

时间:2011-04-20 16:22:29

标签: c# .net algorithm datetime

.NET给出了DateTime结构中本地和UTC时区(或任何其他)的当前时间。

仅给出小时/分钟变量,找到下一次出现的时间段(例如下午6:30 / AM),并能够随意检索更多的未来时间。

这听起来很容易,但朋友确实这已经打破了我的面条好一阵子。

编辑:

示例:

~-------|now|------??-----------|future known time|------------~
~-------2pm------??2-----------9am------------~
??2 = 19

3 个答案:

答案 0 :(得分:1)

如果我理解正确,你想知道要花多少时间才能达到下一个给定的小时:分钟。您可以使用TimeSpan结构。

    //this is your target time from 1 to 12 h
    var future = new TimeSpan(11, 30, 0);

    //TimeOfDay gives you the time elapsed since midnight as a TimeSpan
    var difference = future.Subtract(DateTime.Now.TimeOfDay);

    //check for negative TimeSpan, 
    //it means the target time occurs on the next day, just add 24 hours
    if (difference < TimeSpan.Zero)
        difference = difference.Add(TimeSpan.FromDays(1));

现在你有TimeSpan代表你需要的东西。你可以使用它的属性来表达你认为合适的东西。例如:

    difference.TotalHours; //(double) total time as a fractional hour
    difference.Hours;      //(int) just the hour component of the total time

至于更多的未来时间(上午和下午),您可以再添加12个小时到difference以获得下一次出现。

答案 1 :(得分:0)

这是以stackoverflow形式编码的,因此可能存在一些拼写错误。无论哪种方式,你都会得到全局。

public DateTime search(int hour, int min) {
  if (hour >= 12)
    return partialSearch(hour - 12, hour, min);

  else
    return partialSearch(hour, hour + 12, min);
}

public DateTime partialSearch(int morningHour, int afternoonHour, int min) {
  DateTime now = DateTime.now;

  if (now.hour == morningHour || now.hour == afternoonHour) {
    if (now.minutes <= min) {
      return now.AddMinutes(min - now.minutes);
    }
    now = now.AddHour(1);
  }

  now = now.AddMinutes(-now.Minutes); // set the minutes to 0
  while(now.hour != morningHour || now.hour != afternoonHour) {
    now = now.AddHour(1);
  }

  return now.addMinutes(min);
}

答案 2 :(得分:0)

不确定我是否完全理解您的要求,但似乎您正在寻找类似的东西?

public class TimeIterator
{
    public DateTime CurrDateTime { get; set; }

    public IEnumerable<DateTime> GetTimes(short count)
    {
        for (short i = 1; i <= count; i++)
            yield return this.CurrDateTime.AddHours(i * 12);            
    }

    public TimeIterator()
    {
        this.CurrDateTime = DateTime.Now;
    }
}

可以轻松调整此代码以适用于任何时间间隔 - 而不仅仅是12小时间隔

相关问题