0

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

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

这是我到目前为止所拥有的:

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

但不给我这个月之后的下周。

这正是我正在寻找的:

任何人都可以使用一个函数来帮助完成这项工作。

4

3 回答 3

8
DateTime baseDate = DateTime.Now;
var thisWeekStart = baseDate.AddDays(-(int)baseDate.DayOfWeek);
var thisWeekEnd = thisWeekStart.AddDays(7).AddSeconds(-1);
于 2015-03-04T09:57:05.037 回答
7

尝试这个 :

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
于 2012-10-25T09:38:25.063 回答
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;

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

于 2012-10-20T07:02:29.260 回答