c# - 如何确定日期是否位于当前周日期之间?

标签 c#

在 C# 中,

我们如何检查特定日期和周内日期?

例如:6/02/2014

当前周数:02/02/2014 - 08/02/2014

所以这个日期是在上一周....

最佳答案

使用它来检查(如果你想从 fromDate 开始的 1 周内,最后一个参数是可选的,你不需要使用最后一个参数):

 public static bool DateInside(DateTime checkDate, 
     DateTime fromDate, DateTime? lastDate = null)
 {
     DateTime toDate = lastDate != null ? lastDate.Value : fromDate.AddDays(6d);
     return checkDate >= fromDate && checkDate <= toDate;
 }

调用使用:

bool isDateInside = DateInside(new DateTime(2014, 02, 06), 
     new DateTime(2014, 02, 02)); // return true

然后先搜索 :) 答案也在这里:How to check whether C# DateTime is within a range

如果你想检查日期是否在同一周内,那么你可以使用这个:

public static bool DateInsideOneWeek(DateTime checkDate, DateTime referenceDate)
{
    // get first day of week from your actual culture info, 
    DayOfWeek firstWeekDay = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
    // or you can set exactly what you want: firstWeekDay = DayOfWeek.Monday;
    // calculate first day of week from your reference date
    DateTime startDateOfWeek = referenceDate;
    while(startDateOfWeek.DayOfWeek != firstWeekDay)
    { startDateOfWeek = startDateOfWeek.AddDays(-1d); }
    // fist day of week is find, then find last day of reference week
    DateTime endDateOfWeek = startDateOfWeek.AddDays(6d);
    // and check if checkDate is inside this period
    return checkDate >= startDateOfWeek && checkDate <= endDateOfWeek;
}

我的文化信息中的实际一周从 2014 年 2 月 3 日星期一开始(所以对我来说是 2 月 3 日到 2 月 9 日之间的一周)。如果我检查引用日期(第二个参数)为今天(2014 年 2 月 6 日)的任何日期,我会得到以下结果:

For 2014-Feb-02 (Sunday before this week): false
For 2014-Feb-03 (Monday inside this week): true
For 2014-Feb-06 (Today  inside this week): true
For 2014-Feb-09 (Sunday inside this week): true
For 2014-Feb-10 (Monday next        week): false

您可以调用此方法来检查某个日期是否在同一周内,如下所示:

DateInsideOneWeek(new DateTime(2014, 02, 02), new DateTime(2014, 02, 06));

您可以使用以下代码找到当前一周的开始和结束日期:

DateTime startDateOfWeek = DateTime.Now.Date; // start with actual date
while(startDateOfWeek.DayOfWeek != DayOfWeek.Monday) // set first day of week in your country
{ startDateOfWeek = startDateOfWeek.AddDays(-1d); } // after this while loop you get first day of actual week
DateTime endDateOfWeek = startDateOfWeek.AddDays(6d); // you just find last week day

这是你想要的吗?

关于c# - 如何确定日期是否位于当前周日期之间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21598365/

相关文章:

c# - 在 C# 中使用 ForEach 语句迭代两个数组

c# - 在最小 API 中将参数设置为 .NET Core 中的可选参数

c# - 如何修复这个来自 Nib 的 "Selector invoked ... on a managed object ... that has been GC' ed",其中包含未使用的自定义 UITableViewCell?

c# - C# 有扩展属性吗?

c# - 从 .NET MVC Controller 获取压缩文件并在 javascript 中解压缩

c# - 是否可以限制应用程序域的性能或设置配额?

c# - Windows 8.1 到 10 XAML - 参数不正确异常

c# - 如何在 WCF 和 Silverlight 应用程序上使用相同的类库

c# - 访问 Roslyn REPL 中的 .config 文件

c# - 带 HTTP 2.0 的 RestSharp