到周末的剩余时间结束了

时间:2014-04-14 11:26:24

标签: c#

我想计算在周末结束之前剩下多少秒(比如直到星期日晚上11.59)。当在周末调用操作时,它需要返回TimeSpan。我需要每周这样做,所以我不能设置一个硬编码的'结束如

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

如何设置正确的enddate来计算从现在开始的剩余秒数?

2 个答案:

答案 0 :(得分:3)

尝试:

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

答案 1 :(得分:0)

使用DayOfWeek属性查找到本周末的剩余天数,并通过将DayTime添加到StartDate来创建新的DateTime endDate = startDate.Date.AddDays(7 - (int)startDate.DayOfWeek) 对象。

{{1}}