So I am trying to calculate how long it will be until a specific time. ButI cant seem to get it working.
An example is say im trying to calculate how long it will be from now to 06:00:00am So say it is 10:30pm I want to see how long it will be until til 6am the next day. So the correct answer would be 7 hours and 30 mins. Or another example say it is 8:30pm I want to see how long it will be until 10pm. If anyone could provide me with some code to help it would be greatly appreciated!
CodePudding user response:
Compare the timespan first then add one day if needed.
static TimeSpan TimeDiff(TimeSpan nowSpan, TimeSpan ts)
{
if (nowSpan > ts)
{
ts = ts.Add(TimeSpan.FromDays(1));
}
return ts - nowSpan;
}
static void Main(string[] args)
{
Console.WriteLine(TimeDiff(new TimeSpan(22, 30, 0), new TimeSpan(6, 0, 0)));
// 07:30:00
Console.WriteLine(TimeDiff(new TimeSpan(20, 30, 0), new TimeSpan(22, 0, 0)));
// 01:30:00
// You may want use DateTime.Now.TimeOfDay as the first parameter
Console.ReadKey();
}
CodePudding user response:
Try this
DateTime later = DateTime.Now.AddHours(3);
DateTime now = DateTime.Now;
Console.WriteLine(later.Subtract(now).TotalSeconds);