gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:36:22 24 4
gpt4 key购买 nike

在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com