Home > Back-end >  Creating list of hours separated by 30 min in C#
Creating list of hours separated by 30 min in C#

Time:09-27

I am trying to create this list in c#, add this is what I am at now

enter image description here

public static List<string> GetCurrentTime()
    {
        var start = DateTime.Today;
        List<string> L = new List<string>();
        var clockQuery = from offset in Enumerable.Range(0, 48)
                         select start.AddMinutes(30 * offset);
        foreach (var time in clockQuery)
            L.Add(time.ToString("hh:mm"));

        return L;
    }

This code will generate this list, and I am stuck here, how can I generate the above list which the first value should always start (1 hour after now - 1 hour 30min)

enter image description here

CodePudding user response:

I set my code like the following:

public static List<string> GetCurrentTime()
    {
        var start = DateTime.Today;
        List<string> L = new List<string>();
        var clockQuery = from offset in Enumerable.Range(0, 48)
                         select start.AddMinutes(30 * offset);
        foreach (var time in clockQuery)
        {
            if(time > DateTime.Now)
            {
                L.Add(time.ToString("hh:mm")   " - "   time.AddMinutes(30).ToString("hh:mm"));
            }
        }
            

        return L;
    }

This will result to the following list and it worked for me

enter image description here

CodePudding user response:

If you want time from mid-night :

 public static List<string> GetCurrentTime()
 {
   var now = DateTime.Now;
   var start = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);
   List<string> L = new List<string>();
   var clockQuery = from offset in Enumerable.Range(0, 48)
                   select start.AddMinutes(30 * offset);
  foreach (var time in clockQuery)
   {
     L.Add(time.ToString("hh:mm")   "-"   
           time.AddMinutes(30).ToString("hh:mm"));
   }
  return L;
}
  • Related