繁体   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