skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    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


  2. 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;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search