如何获得一个月历视图的第一天和最后一天(周日到周六)(How to get the first an

2019-10-20 16:33发布

我有一个日历的第一周开始一天在周日周六结束。

现在我只能在日历当月禁用天,因为我不知道在日历中的第一天和最后一天。

即时通讯使用的代码现在的问题是非常简单的:

private List<DateTime> GetDisabledDates(DateTime fromDate, DateTime toDate){

// right now fromDate and toDate are the start and end days in a month

var disabledDates = SearchDates(fromDate, toDate);

return disabledDates;

}

所以,我需要的是让第一天与最后一天显示,在日历月,考虑到本周日开始在周六结束。

如何dinamically获得第一个和最后任何线索(黄标日期)从一个特定的月份? 考虑到日历配置?

Answer 1:

那么在这种观点的东西第一天这样应该这样做

//Using UTC to counter daylight saving problems
var month = new DateTime(2014, 8, 1, 0, 0, 0, DateTimeKind.Utc); 
var firstInView = month.Subtract(TimeSpan.FromDays((int) month.DayOfWeek));

对于余下的日子里,你只需要计算留在(7个* numRows行)的金额 - (DaysOfCurrentMonth + DaysOfPreviousMonth),其中DaysOfPreviousMonth是这个月的星期几财产再第一天。



Answer 2:

这对我的作品的解决方案:

int totalCalendarDays = 42; // matrix 7 x 6

// set the first month day
DateTime firstDayMonth = new DateTime(date.Year, date.Month, 1);

 // set the lastmonth day
DateTime lastDayMonth = new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year, date.Month));

// now get the first day week of the first day month (0-6 Sun-Sat)
byte firstDayWeek = (byte) firstDayMonth.DayOfWeek;

// now get the first day week of the last day month (0-6 Sun-Sat)
byte lastDayWeek = (byte) lastDayMonth.DayOfWeek;

// now the first day show in calendar is the first day month minus the days to 0 (sunday)
DateTime firstDayCalendar = firstDayMonth.Subtract(TimeSpan.FromDays(firstDayWeek));
int tempDays = (lastDayMonth - firstDayCalendar).Days;

DateTime lastDayCalendar = lastDayMonth.Add(TimeSpan.FromDays(totalCalendarDays - tempDays - 1));

也许是一个更好的办法来做到这一点:)



Answer 3:

Here's我的建议,确定年份和月份作为参数:

public DateTime[] GetMonthDisplayLimits(int year, int month)
{
    int lastDay = DateTime.DaysInMonth(year, month);
    var firstDayInMonth = new DateTime(year, month, 1);
    var lastDayInMonth = new DateTime(year, month, lastDay);

    var firstDayInView = firstDayInMonth.AddDays(-1 * (int) firstDayInMonth.DayOfWeek);
    var lastDayInView = lastDayInMonth.AddDays((int) (6 - lastDayInMonth.DayOfWeek));

    return new DateTime[] { firstDayInView, lastDayInView };
}

DateTime[] monthDisplayLimits = GetMonthDisplayLimits(2014, 8);

var firstDayInView = monthDisplayLimits[0];
var lastDayInView  = monthDisplayLimits[1];

由于“星期几”是0和6之间的值,这种做法几轮下来的第一个周日和围捕的最后一个工作日。



文章来源: How to get the first and last day of a month calendar view (sunday-saturday)