簡體   English   中英

如何找到過去一周的日期范圍? 周日至周六,但不得超過所屬月份

[英]How to find the date range of the past week? Sunday to Saturday but should not exceed the month it belongs to

我需要一種算法來獲取周日至周六的過去一周的日期

該應用程序將在每個星期一運行

示例:今天的日期是2014年9月1日(星期一)
結果應為: 8月24日(星期日)-8月30日(星期六)
但由於8月31日是8月的最后一天,因此應將其包括在內。

另一個示例:2014年10月6日(星期一)
結果應為: Oct 1(星期三)至4(星期六)

因此,基本上,應該考慮到輸出應該是它所屬月份的范圍。 我們決不能讓幾個月彼此交叉。 我將非常感謝我所能提供的所有幫助。 謝謝!

這應該是您正在尋找的:

public static class Week
{
    public static IEnumerable<DateTime> UpTo(DateTime upTo)
    {
        var lastMonday = upTo.DayOfWeek == DayOfWeek.Sunday
            ? upTo.AddDays(-6)
            : upTo.AddDays(-(int) upTo.DayOfWeek + 1);
        var lastSunday = lastMonday.AddDays(-1);
        var sundayBefore = lastSunday.AddDays(-7);

        var firstDayOfMonth = new DateTime(lastSunday.Year, lastSunday.Month, 1);
        var startDay = firstDayOfMonth >= sundayBefore ? firstDayOfMonth : sundayBefore;

        for (var day = startDay; day < lastSunday; day = day.AddDays(1))
            yield return day;
    }
}

我認為代碼很lastMonday解釋-也許唯一不清楚的地方是我計算lastMonday的行-為此,您必須知道DayOfWeekMonday1的枚舉-所以我得到了代表當天的數字的周數,並相應減去天數。 不幸的是,我首先錯過了一個極端情況: Sunday為0,所以如果您從星期日開始,它將在下一個星期一得到-這就是為什么要在其中附加檢查的原因-以防萬一您不能保證給出星期一規則。

這是兩個檢查您的條件的Xunit測試用例:

[Fact]
public void SepTest()
{
    var sunday = new DateTime(2014, 8, 24);
    var expected = Enumerable.Range(0, 7).Select(d => sunday.AddDays(d));

    var week = Week.UpTo(new DateTime(2014, 9, 1));
    Assert.Equal(expected, week);
}

[Fact]
public void OctTest()
{
    var wednesday = new DateTime(2014, 10, 1);
    var expected = Enumerable.Range(0, 4).Select(d => wednesday.AddDays(d));

    var week = Week.UpTo(new DateTime(2014, 10, 6));
    Assert.Equal(expected, week);
}

[Fact]
public void Day_EdgeCase()
{
    var sunday = new DateTime(2014, 8, 24);
    var expected = Enumerable.Range(0, 7).Select(d => sunday.AddDays(d));

    var week = Week.UpTo(new DateTime(2014, 9, 7));
    Assert.Equal(expected, week);
}

這是我寫的可能不太好,但可能對您有所幫助。

DateTime currentDate = DateTime.Now;
    //currentDate = DateTime.Parse("9/8/2014");       //Just for test.

    List<PastWeekDays> list = new List<PastWeekDays>();
    //Started loop from 2 beacause it will pick current datetime every monday,so 2 days ago will be saturday.
    for (int i =2; i < 9; i++)
    {
        DateTime lastDate = currentDate.AddDays(-double.Parse((i).ToString()));
        if (lastDate.Month != currentDate.Month)
            break;
        PastWeekDays day = new PastWeekDays();
        day.Date = lastDate.Day.ToString();
        day.DayName = lastDate.DayOfWeek.ToString();
        list.Add(day);
    }

//This is custom class you may not need it.
public class PastWeekDays
{
public string Date { get; set; }
public string DayName { get; set; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM