-2

I have this function that returns a range of times (between two TimeSpan ) by incrementing an hour.

 public static IEnumerable < TimeSpan > Range(TimeSpan start, TimeSpan end) {
     for (var dt = start; dt <= end; dt = dt.Add(new TimeSpan(1, 0, 0))) {
         yield
         return dt;
     }
 }

 // As an example
 TimeSpan start = new TimeSpan(09, 0, 0);
 TimeSpan end = new TimeSpan(12, 0, 0);
 var range = Range(start.Ticks, end.Ticks);

Result :

09:00:00
10:00:00
11:00:00
12:00:00

What I would like to get is a time range ( increment by minutes instead of hours ):

Expected result:

09:00:00
09:01:00
09:02:00
09:03:00
  ...
11:59:00
12:00:00

What can I do to make this works?

  • 1
    So you have the code that increments by 1 hour, and now you want to change it to increment 1 minute. What is the problem here? Surely given the code you have you can make a stab at solving this. – Jamiec Jul 05 '21 at 15:37
  • I have already test the increment using minutes but it add one minute in every hour and not 60 minutes – csharp_devloper31 Jul 05 '21 at 15:38
  • _"I have already test the increment using minutes but it add one minute in every hour and not 60 minutes"_ -- there's no clear reason why changing `new TimeSpan(1,0,0)` in the code you posted to `new TimeSpan(0,1,0)` (the most obvious change that would match what you _claimed_ to have done) would not result in the correct output. But you didn't bother to provide _that_ code, i.e. the code you attempted but which doesn't work, so there's no way to usefully answer the question. Please read [mcve] and [ask]. – Peter Duniho Jul 05 '21 at 15:55

1 Answers1

2

Please read the Documentation for the TimeSpan constructor.

public TimeSpan (int hours, int minutes, int seconds);

Change the assignment in your for-loop to

dt = dt.Add(new TimeSpan(0,1,0))

since the second parameter refers to the minutes. The first one is the hours. Or you can use

dt = dt.Add(TimeSpan.FromMinutes(1))

to make it more clear when reading the code later.

Torben Schramme
  • 2,104
  • 1
  • 16
  • 28