C#学习教程:查找上一个完成周的周结束日期分享


查找上一个完成周的周结束日期

对于任何给定日期,如果您的周从周日到周六,您将如何找到上一个完整周的周结束日期?

 DateTime StartOfWeek = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek); DateTime EndOfLastWeek = StartOfWeek.AddDays(-1); 

 DateTime givenDate; // = ... int daysToOffset = ((int)givenDate.DayOfWeek + 1) * -1; DateTime lastDayOfLastCompletedWeek = givenDate.AddDays(daysToOffset); 

.NET DateTimes公开DayOfWeek属性。 在这种情况下,您可以利用它:

 var currDay = DateTime.Today.DayOfWeek; //currday is now an enumeration with Sunday=0, Saturday=6 //We can cast that to a number and subtract to get to the previous Saturday var EndOfLastWeek = DateTime.Today.AddDays(((int)currDay+1)*-1); 

  public static DateTime EndOfWeek(DateTime dateTime) { DateTime start = StartOfWeek(dateTime); return start.AddDays(6); } public static DateTime StartOfWeek(DateTime dateTime) { int days = dateTime.DayOfWeek - DayOfWeek.Monday; if (days < 0) days += 7; return dateTime.AddDays(-1 * days).Date; } 

要查找上周结束,只需致电:

  DateTime endPrevWeek = StartOfWeek(DateTime.Today).AddDays(-1); 

如果要指定哪一天是星期结束,并且您不想担心系统定义为星期的默认开始日期,请使用以下方法:

上述就是C#学习教程:查找上一个完成周的周结束日期分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注---猴子技术宅(www.ssfiction.com)

 private static DateTime GetPreviousSpecifiedDayOfWeek(DateTime dt, DayOfWeek day) { if (dt.DayOfWeek == day) { return dt; } while (dt.DayOfWeek != day) { dt = dt.AddDays(-1); } return dt; } 

本文来自网络收集,不代表猴子技术宅立场,如涉及侵权请点击右边联系管理员删除。

如若转载,请注明出处:https://www.ssfiction.com/ckf/959954.html

发表评论

邮箱地址不会被公开。 必填项已用*标注