2

How could calculate the time until the daytime of the next weekday?
More specifically I want to calculate the minutes, hours, and days until the next Wednesday at 14:00.

How could I do that?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Ian H.
  • 3,840
  • 4
  • 30
  • 60

3 Answers3

2

Feel like taking risk to answer that but..

How could calculate the time until the daytime of the next weekday?

If you mean Wednesday with this sentence, you can iterate current date to next Wednesday with DayOfWeek enumeration like;

DateTime today = DateTime.Today;
while (today.DayOfWeek != DayOfWeek.Wednesday)
{
    today = today.AddDays(1);
}

Since I'm in İstanbul right now -today is Wednesday- and this code returns today, not 7 days after.

More specifically I want to calculate the minutes, hours, and days until the next Wednesday at 14:00.

Then you can add 14 hour to today and get difference between current local time (DateTime.Now) with it.

today = today.AddHours(14);
TimeSpan difference = DateTime.Now - today;
Console.WriteLine(difference.ToString("d\\.hh\\:mm"));

By the way, this TimeSpan.ToString(string) overload added with .NET Framework 4.0 version. If you use .NET 3.5 or below, you can use Days, Hours or Minutes properties (or maybe TotalXXX properties) of your difference.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
1

That you need is a TimeSpan object:

TimeSpan duration = nextWednesday  - currentDate;

where nextDay and nextWednesday are two DateTime objects representing the dates you are interested in.

For instance, currentDate could be this DateTime.Now. For nextWednesday you need something more:

var today = DateTime.Today;
var daysUntilWednesday = ((int) DayOfWeek.Wednesday - (int) today.DayOfWeek + 7) % 7;
var nextWednesday = today.AddDays(daysUntilWednesday);
var ts = new TimeSpan(14,0,0);
nextWednesday = nextWednesday.Date + ts;

Having done that, you can use the properties of TimeSpan object to get that you want.

Christos
  • 53,228
  • 8
  • 76
  • 108
1

You can try using TimeSpan

DateTime t1 = ......;
DateTime t2 = ......;
TimeSpan ts = t1.Subtract(t2);

A TimeSpan object represents a time interval (duration of time or elapsed time) that is measured as a positive or negative number of days, hours, minutes, seconds, and fractions of a second. The TimeSpan structure can also be used to represent the time of day, but only if the time is unrelated to a particular date.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331