Carl900
Carl900

Reputation: 15

Calculating next time and rounding date-time

I have datetime like 2019-02-10 20:39:23 and I want to round this time to the next one apart 15 min to the closest one. So it means the next one should be 2019-02-10 21:45:00 or another example 21:24:17 should became 21:45:00... The code below works fine until I have datetime like 2019-02-10 23:54:20. Then the next one rounded should be 2019-03-10 00:00:00 but I get 2019-02-10 00:00:00.

Here is how I'm doing it:

static void Main(string[] args)
{
    DateTime dt = DateTime.Parse("2019-02-10 23:54:23");

    var interval = TimeSpan.FromMinutes(15);

     DateTime last = NextTime(dt, interval);

     Console.WriteLine(last);

    }

    private static DateTime NextTime(DateTime value, TimeSpan interval)
    {
        var temp = value.Add(new TimeSpan(interval.Ticks / 2));
        var time = new TimeSpan((temp.TimeOfDay.Ticks / interval.Ticks) * interval.Ticks);

        return value.Date.Add(time);
    }

For output I get 2019-02-10 00:00:00 instead of 2019-03-10 00:00:00

Can't figure out why doesn't turn to next day...

Upvotes: 1

Views: 60

Answers (2)

Using DateTime.Add(TimeSpan) the time is concat in the date.

I'v changed your code in this way and it did the trick:

    private static DateTime NextTime(DateTime value, TimeSpan interval)
    {
        var temp = value.Add(new TimeSpan(interval.Ticks / 2));
        var time = new TimeSpan((temp.TimeOfDay.Ticks / interval.Ticks) * interval.Ticks);
        if (time == new TimeSpan(0, 0, 0)) { time = new TimeSpan(24, 0,0); }
        var timeDiff = time - value.TimeOfDay;

        var finalDate = value.AddHours(timeDiff.Hours);
        finalDate = finalDate.AddMinutes(timeDiff.Minutes);
        finalDate = finalDate.AddSeconds(timeDiff.Seconds);

        return finalDate;
    }

I believe that must have some way more beautifull to do that but it works.

Upvotes: 0

dvo
dvo

Reputation: 2153

The return value is being calculated from the wrong variable. Use temp instead of value:

 private static DateTime NextTime(DateTime value, TimeSpan interval)
 {
     var temp = value.Add(new TimeSpan(interval.Ticks / 2));
     var time = new TimeSpan((temp.TimeOfDay.Ticks / interval.Ticks) * interval.Ticks);

     return temp.Date.Add(time);
 }

The reason for this is because you're adding your interval to the value. If it rolls over a midnight/end of day your value.Date will return the wrong day. Since you store temp, you can return temp.Date.Add(time)

Upvotes: 1

Related Questions