JamesWat JamesWat - 3 months ago 19
C# Question

c# datetime create Day of Week Hour and Min

How do i go about creating a datetime based on only the following information:
Day of Week, Hour & Minuet.

I.e. I don't care what month it is or even what the date is (i don't have that info in the database).

I thought i could parse them as a string but is turning out to be more difficult than i thought.


Created on function for you it might be helpful to you ..

   public DateTime CreateDayOfWeek(int DayOfWeek,int hour,int min)
            DateTime dt = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,hour,min,0);

            // The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
            int daysUntilTuesday = (DayOfWeek - (int)dt.DayOfWeek + 7) % 7;
            //  DateTime nextTuesday = today.AddDays(daysUntilTuesday);

            dt = dt.AddDays(daysUntilTuesday);

            return dt;

I have tested for several dates and its working for me .. let me know if you have any issue ..

Here is .netFiddle