在我的程序中有两个datetimepickers。我需要在所选日期之间获取日期并将它们存储到列表或数组中。所有这些都将在第二个datetimepicker值更改事件
中完成private void dateTimePickertodate_ValueChanged(object sender, EventArgs e)
{
if (dateTimePickertodate.Value <=dateTimePickerfromdate.Value)
{
MessageBox.Show("Choose Correct date");
textBoxnumofdays.Clear();
}
else
{
cleave = new LeaveApplication(constr);
TimeSpan span = dateTimePickertodate.Value - dateTimePickerfromdate.Value;
if (Mode == 1)
{
textBoxnumofdays.Text = Convert.ToString(span.Days + 2);
}
else
{
textBoxnumofdays.Text = Convert.ToString(span.Days + 1);
}
}
}
答案 0 :(得分:4)
你可以尝试这些方面的东西
DateTime dtFrom = new DateTime(2011, 02, 5);
DateTime dtTo = new DateTime(2011, 02, 9);
List<DayOfWeek> days = new List<DayOfWeek>();
while (dtTo != dtFrom)
{
dtFrom = dtFrom.AddDays(1);
days.Add(dtFrom.DayOfWeek);
}
天将有你的工作日列表(如果这是你想要的那样)
答案 1 :(得分:2)
public List<DateTime> GetSelectedDaysInPeriod(DateTime startDate, DateTime endDate, List<DayOfWeek> daysToCheck)
{
var selectedDates = new List<DateTime>();
if (startDate >= endDate)
return selectedDates; //No days to return
if (daysToCheck == null || daysToCheck.Count == 0)
return selectedDates; //No days to select
try
{
//Get the total number of days between the two dates
var totalDays = (int)endDate.Subtract(startDate).TotalDays;
//So.. we're creating a list of all dates between the two dates:
var allDatesQry = from d in Enumerable.Range(1, totalDays)
select new DateTime(
startDate.AddDays(d).Year,
startDate.AddDays(d).Month,
startDate.AddDays(d).Day);
//And extracting those weekdays we explicitly wanted to return
var selectedDatesQry = from d in allDatesQry
where daysToCheck.Contains(d.DayOfWeek)
select d;
//Copying the IEnumerable to a List
selectedDates = selectedDatesQry.ToList();
}
catch (Exception ex)
{
//Log error
//...
//And re-throw
throw;
}
return selectedDates;
}
答案 2 :(得分:1)
此问题已在此处得到解答: http://bytes.com/topic/net/answers/48324-their-method-timespan-time-function
此外,您希望使用TimeSpan的TotalDays属性而不仅仅是当天。
答案 3 :(得分:0)
2个DateTimes的差异是TimeSpan,它具有属性TotalDays,即2个日期时间之间的天数