0

I have start time in format hh:mm:ss and then entering duration in hours and selecting a day of week.

I want to calculate the end time based on above parameters.

For Example: of start time is 00:00:00 and duartion entered is 48 hours with day of week as Sunday. The end time must be 00:00:00 hrs on Tuesday.

How to do it?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
BAPSDude
  • 331
  • 1
  • 4
  • 16
  • 3
    Please read this link http://stackoverflow.com/questions/12521366/getting-time-span-between-two-times-in-c Hope it help. – Ragesh P Raju Sep 26 '13 at 04:52

5 Answers5

2
public static void Main()
{
    var today = "Sunday";
    DayOfWeek dw;
    DayOfWeek.TryParse(today, true, out dw);
    int hours = 48;
    int days = hours / 24;
    int remainder = hours % 24;
    DayOfWeek endDay = dw + days;
    Console.Write("End time: {0} at {1}", endDay, remainder);
} 
crthompson
  • 15,653
  • 6
  • 58
  • 80
  • Keep in mind due to leaps/DST/etc., adding 48 hours won't always result in exactly two `DayOfWeek`s passing keeping the same time. – Cory Nelson Sep 26 '13 at 05:04
1

Consider using the DateTime.AddHours() function

Nadeem_MK
  • 7,533
  • 7
  • 50
  • 61
1

Add a TimeSpan to a DateTime :

var today = System.DateTime.Now;
var duration = new System.TimeSpan(48, 0, 0, 0);
var endDateTime= today.Add(duration);
Pascalz
  • 2,348
  • 1
  • 24
  • 25
1
string start = "00:00:00";
DayOfWeek startDay = DayOfWeek.Sunday;
int duration = 48;
DateTime date = DateTime.Parse(start);
while(date.DayOfWeek != startDay)
{
    date = date.AddDays(1);
}
date = date.AddHours(duration);

DayOfWeek resultDay = date.DayOfWeek;
string time = date.ToLongTimeString();
x2.
  • 9,554
  • 6
  • 41
  • 62
1

try this:

//assuming that you have a validation for your startTime that this will always on this format "HH:mm:ss"
private static string GetEndTime(string startTime, int duration, DayOfWeek dayOfWeek)
{
    DateTime startDateTime = DateTime.Parse(startTime);
    DateTime endDateTime = startDateTime.AddHours(duration);

    return endDateTime.ToString("HH:mm:ss");
}

private static DayOfWeek GetEndDay(int duration, DayOfWeek dayOfWeek)
{
    int days = duration / 24;
    DayOfWeek endDay = dayOfWeek + days;

    return endDay;
}

static void Main()
{
    string testStartTime = "00:00:00";
    DayOfWeek startDay = DayOfWeek.Sunday;
    int duration = 48;

    string endTime = GetEndTime(testStartTime, duration, startDay);
    DayOfWeek endDay = GetEndDay(duration, startDay);
    Console.WriteLine("End Time is {0} hours on {1}", endTime, endDay.ToString());

}
jomsk1e
  • 3,585
  • 7
  • 34
  • 59