我有一个日历,第一周的第一周开始于星期日,结束于星期六。
现在我只能禁用当前日历中的日期,因为我不知道日历中的第一天和最后一天。
我现在使用的代码非常简单:
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;
}
所以,我需要的是在第一天和最后一天显示在日历月,考虑到周从星期日开始到星期六结束。
有关如何从特定月份获得第一个和最后一个(黄色标记日期)的任何线索?考虑日历配置?
答案 0 :(得分: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再次是本月第一天的DayOfWeek属性。
答案 1 :(得分:1)
适合我的解决方案:
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));
也许是一种更好的方法:)
答案 2 :(得分:0)
这是我的建议,将年份和月份定义为参数:
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];
由于“DayOfWeek”是介于0和6之间的值,因此这种方法会在第一个工作日向下舍入并向上舍入最后一个工作日。