簡體   English   中英

從DateTime對象計算星期一至星期日的星期

[英]Calculate Monday-Sunday week from a DateTime object

我正在嘗試編寫一種方法,該方法將返回代表周一至周的DateTimes列表。 它應該采用給定的DateTime並使用它來計算周圍的日期

它計算確定的開始日期,但是當它遇到最后一個循環時問題就開始了。 在每次運行DateTime變量時,tmpDate應該增加1天,然后添加到列表中。 但是,按現狀,我要返回一個包含7個開始日期的列表。

誰能看到我要去哪里錯了(我有種感覺,我可能看起來像個簡單的人:))?
另外,如果這是一個經常問到的問題,則表示歉意。 可能會看到很多開始日期/結束日期和星期數類型的問題,但沒有一個專門處理此類問題。

private List<DateTime> getWeek(DateTime enteredDate)
{ 
    /* Create List to hold the dates */
    List<DateTime> week = new List<DateTime>();
    int enteredDatePosition = (int)enteredDate.DayOfWeek;

    /* Determine first day of the week */
    int difference = 0;

    for (int i = 0; i < 7; i++)
    {
        difference++;
        if (i == enteredDatePosition)
        {
            break;
        }
    }
    // 2 subtracted from difference so first and enteredDatePostion elements will not be counted. 
    difference -= 2;

    DateTime startDate = enteredDate.Subtract(new TimeSpan(difference, 0, 0, 0));
    week.Add(startDate);

    /* Loop through length of a week, incrementing date & adding to list with each iteration */
    DateTime tmpDate = startDate;

    for (int i = 1; i < 7; i++)
    {
        tmpDate.Add(new TimeSpan(1, 0, 0, 0));
        week.Add(tmpDate);
    }
    return week;
}

DateTime是不可變的。
tmpDate.Add(...)返回一個新的DateTime,並且不修改tmpDate

您應該編寫tmpDate = tmpDate.AddDays(1)tmpDate += TimeSpan.FromDays(1)

我相信此代碼段是針對周日谷周六量身定制的,但是您可以嘗試以下操作:

DateTime ToDate = DateTime.Now.AddDays((6 - (int)DateTime.Now.DayOfWeek) - 7);
DateTime FromDate = ToDate.AddDays(-6);

您使算法變得比所需的復雜。 查看以下工作片段:

using System;
using System.Collections.Generic;

public class MyClass
{
    public static void Main()
    {
        // client code with semi-arbitrary DateTime suuplied
        List<DateTime> week = GetWeek(DateTime.Today.AddDays(-2));
        foreach (DateTime dt in week) Console.WriteLine(dt);
    }

    public static List<DateTime> GetWeek(DateTime initDt)
    {
        // walk back from supplied date until we get Monday and make 
        // that the initial day
        while (initDt.DayOfWeek != DayOfWeek.Monday) 
            initDt = initDt.AddDays(-1.0);

        List<DateTime> week = new List<DateTime>();

        // now enter the initial day into the collection and increment
        // and repeat seven total times to get the full week
        for (int i=0; i<7; i++)
        { 
            week.Add(initDt);
            initDt = initDt.AddDays(1.0);
        }

        return week;
    }
}

暫無
暫無

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

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