我有两个datetimepickers
。所以我希望得到所选值之间的星期几。
示例:date1 = 14/1/2015
和date2 = 17/1/2015
所以结果应该是:days = Wed. Thu. Fri. Sat.
答案 0 :(得分:5)
您希望在两个日期之间获得所有DayOfWeek
的{{1}}个?
DateTime
您需要添加int daysDiff = (date2 - date1).Days;
List<DayOfWeek> days = Enumerable.Range(0, daysDiff + 1) // +1 because you want to include start and end date
.Select(d => date1.AddDays(d).DayOfWeek)
.ToList();
答案 1 :(得分:2)
您可以轻松地迭代DateTime
值,例如;
var dt1 = new DateTime(2015, 1, 14);
var dt2 = new DateTime(2015, 1, 17);
while (dt2 >= dt1)
{
Console.WriteLine(dt1.DayOfWeek);
dt1 = dt1.AddDays(1);
}
结果将是;
Wednesday
Thursday
Friday
Saturday
如果您希望将abbreviated day names改为Wed, Thu, Fri, Sat
,则可以将"ddd"
custom format specifier与基于英语的文化(如InvariantCulture
)一样使用;
var dt1 = new DateTime(2015, 1, 14);
var dt2 = new DateTime(2015, 1, 17);
while (dt2 >= dt1)
{
Console.WriteLine(dt1.ToString("ddd", CultureInfo.InvariantCulture));
dt1 = dt1.AddDays(1);
}
答案 2 :(得分:0)
另一种替代方案,包括非常规使用for循环和yield return
语句:
void Main()
{
var daysOfWeek = DaysBetween(
new DateTime(2015, 1, 14),
new DateTime(2015, 1, 17));
Console.WriteLine(
String.Join(", ", daysOfWeek.Select(d => d.ToString().Substring(0, 3))));
// prints: Wed, Thu, Fri, Sat
}
IEnumerable<DayOfWeek> DaysBetween(DateTime start, DateTime end)
{
for (var dateTime = start; dateTime <= end; dateTime = dateTime.AddDays(1))
{
yield return dateTime.DayOfWeek;
}
}