Home > front end >  How can I round down DateTime but 23 times?
How can I round down DateTime but 23 times?

Time:10-15

for (int i = 0; i < 23; i  )
{
    var dt = RoundDown(DateTime.Now, TimeSpan.FromMinutes(5));
    datestimes.Add(dt);
}

And

DateTime RoundDown(DateTime date, TimeSpan interval)
{
    return new DateTime(
        (long)Math.Floor(date.Ticks / (double)interval.Ticks) * interval.Ticks
    );
}

datestimes is List<DateTime>

I need to make that the first time to be rounded will be the current DateTime.Now for example if it's 23:44 then round it down to 23:40 and this is what happens now.

But from this point I want to round down more 22 times for example 23:40, 23:35, 23:30, 23:25 like that more 22 times and to add each time the rounded date time to the List

CodePudding user response:

Only do the round down once, Then subtract the interval, instead of rounding.

DateTime dt = RoundDown(DateTime.Now, TimeSpan.FromMinutes(5));

While(dt.minutes != 0)
{
  //your code
  dt.AddMinutes(-5;)
}

CodePudding user response:

Declare the DateTime.Now variable before the loop. Get the minutes and get the rounded value. And then run a for loop and keep on decreasing the minutes by 5 and add to your list.

To get the largest number smaller than or equal to a number N and divided by K you can write the simple method.

int findNum(int N, int K)
{
    int rem = N % K;
 
    if (rem == 0)
        return N;
    else
        return N - rem;
}

In your case K is 5.

CodePudding user response:

You forgot to actually decrease the date value that is being rounded down, which can be done with .AddMinutes(-5 * i).

Besides that, it's also more efficient to calculate the date only once. Doing so then also prevents race conditions in case your code runs while the clock changes behind the scenes to the next 5-minute interval.

Improved code:

var startDate = DateTime.Now;
for (int i = 0; i < 23; i  )
{
    var dt = RoundDown(startDate.AddMinutes(-5 * i), TimeSpan.FromMinutes(5));
    Console.WriteLine(dt);
}

Working demo: https://dotnetfiddle.net/6o5HyW

  •  Tags:  
  • c#
  • Related