stefjnl
stefjnl

Reputation: 732

Remaining time until weekend is over

I want to calculate how many seconds there are left until the weekend is over (say until Sunday 11.59PM). when the operation is called in the weekend it needs to return a TimeSpan. I need to do this on a weekly basis so i cant set a 'hard-coded' enddate like

new DateTime(2014, 04, 17, 23, 12, 33);

how do i set a correct enddate to calculate the remaining seconds from now?

Upvotes: 0

Views: 390

Answers (2)

Zaheer Ahmed
Zaheer Ahmed

Reputation: 28548

Try:

public static void Main(string[] args) {
    //Your code goes here
    TimeSpan span = (Next(DateTime.Now, DayOfWeek.Sunday).Date + new TimeSpan(23, 59, 00)).Subtract(DateTime.Now);          
    Console.WriteLine(span.TotalSeconds);
}
public static DateTime Next(DateTime from, DayOfWeek dayOfWeek) {
   int start = (int) from.DayOfWeek;
   int target = (int) dayOfWeek;
   if (target <= start) target += 7;
     return from.AddDays(target - start);
}

Here is Demo

Upvotes: 3

chaliasos
chaliasos

Reputation: 9783

Use the DayOfWeek property to find the remaining number of days till the end of the week and create a new DayTime object by adding them to the StartDate.

DateTime endDate = startDate.Date.AddDays(7 - (int)startDate.DayOfWeek)

Upvotes: 0

Related Questions