需要功能才能获得当周的第一天和最后一天

时间:2012-10-20 06:52:22

标签: c# datetime datetime-format dayofweek

我有两个标签第一天和最后一天,我想在按钮点击时更新它。

我需要功能获取当前日期的第一天和最后一天,以便我可以点击下一个和上一个按钮显示它。

这是我到目前为止所做的:

CultureInfo cultureInfo = CultureInfo.CurrentCulture; 
DayOfWeek firstDay = cultureInfo.DateTimeFormat.FirstDayOfWeek; 
firstDayInWeek = dayInWeek.Date; 
lastDayInWeek = dayInWeek.Date; 
while (firstDayInWeek.DayOfWeek != firstDay) 
    firstDayInWeek = firstDayInWeek.AddDays(-1);

但是在本月之后的下一周没有给我。

这正是我正在寻找的:

任何人都可以帮助使用单一功能使其工作。

3 个答案:

答案 0 :(得分:6)

试试这个:

private static void GetWeek(DateTime now, CultureInfo cultureInfo, out DateTime begining, out DateTime end)
{
    if (now == null)
        throw new ArgumentNullException("now");
    if (cultureInfo == null)
        throw new ArgumentNullException("cultureInfo");

    var firstDayOfWeek = cultureInfo.DateTimeFormat.FirstDayOfWeek;

    int offset = firstDayOfWeek - now.DayOfWeek;
    if (offset != 1)
    {
        DateTime weekStart = now.AddDays(offset);
        DateTime endOfWeek = weekStart.AddDays(6);
        begining = weekStart;
        end = endOfWeek;
    }
    else
    {
        begining = now.AddDays(-6);
        end = now;
    }
}

用法示例:

DateTime begining;
DateTime end;

var testDate = new DateTime(2012, 10, 10);
GetWeek(testDate, new CultureInfo("fr-FR"), out begining, out end);
Console.WriteLine("Week {0} - {1}", 
                  begining.ToShortDateString(), 
                  end.ToShortDateString()); // will output Week 10/8/2012 - 10/14/2012

答案 1 :(得分:4)

DateTime baseDate = DateTime.Now;
var thisWeekStart = baseDate.AddDays(-(int)baseDate.DayOfWeek);
var thisWeekEnd = thisWeekStart.AddDays(7).AddSeconds(-1);

答案 2 :(得分:0)

因此,点击一下按钮就会有一周的时间。可以说这是由开始日期定义的。 DateTime结构有一个属性DayOfWeek,它返回类似DayOfWeek.Sunday的枚举。所以这里有一个可能有用的代码片段:

var startOfWeek = DateTime(xx, yy ...); // defined by your business code

var firstDayOfWeek = startOfWeek.DayOfWeek;
var lastDayOfWeek = firstDayOfWeek.AddDays(6).DayOfWeek;

我没有直接编译这段代码,所以希望它没问题。