我有格式 hh:mm:ss 的开始时间,然后以小时为单位输入持续时间并选择一周中的某一天。
我想根据上述参数计算结束时间。
例如:开始时间是 00:00:00,输入的时间是 48 小时,星期天是星期天。结束时间必须是星期二的 00:00:00。
怎么做?
我有格式 hh:mm:ss 的开始时间,然后以小时为单位输入持续时间并选择一周中的某一天。
我想根据上述参数计算结束时间。
例如:开始时间是 00:00:00,输入的时间是 48 小时,星期天是星期天。结束时间必须是星期二的 00:00:00。
怎么做?
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);
}
考虑使用DateTime.AddHours()函数
将 TimeSpan 添加到 DateTime :
var today = System.DateTime.Now;
var duration = new System.TimeSpan(48, 0, 0, 0);
var endDateTime= today.Add(duration);
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();
尝试这个:
//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());
}