我想提取当月的所有星期日,并提供以下代码:
private string GetDatesOfSundays(DateTime DatMonth)
{
string sReturn = "";
int iDayOffset = DatMonth.Day - 1;
DatMonth = DatMonth.AddDays(System.Convert.ToDouble(-DatMonth.Day + 1));
DateTime DatMonth2 = DatMonth.AddMonths(1).AddDays(System.Convert.ToDouble(-1));
while (DatMonth < DatMonth2)
{
if (DatMonth.DayOfWeek == System.DayOfWeek.Sunday)
{
if (sReturn.Length > 0) sReturn += ",";
sReturn += DatMonth.ToShortDateString();
}
DatMonth = DatMonth.AddDays(1.0);
}
return sReturn;
}
[HttpGet]
public ActionResult TradeUKKPISearchesData()
{
string allSundaysInMonth = GetDatesOfSundays(System.DateTime.Now);
//var reportData = _reportingService.GetTradeUKKPISearches();
//return View(reportData);
}
问题在于我的所有类型字符串for allSundaysInMonth,并且也是空的。 sReturn是字符串类型,但我再次传递一个日期(我知道:))但是allSundaysInMonth应该是什么类型? sReturn确实有正确的日期...我需要在控制器视图的下拉列表中显示这些日期,以便用户可以选择他/她需要为其运行报告的任何星期日。
感谢
答案 0 :(得分:5)
怎么样
private IEnumerable<DateTime> GetDatesOfSundays(DateTime DatMonth)
{
int iDayOffset = DatMonth.Day - 1;
DatMonth = DatMonth.AddDays(System.Convert.ToDouble(-DatMonth.Day + 1));
DateTime DatMonth2 =
DatMonth.AddMonths(1).AddDays(System.Convert.ToDouble(-1));
while (DatMonth < DatMonth2)
{
if (DatMonth.DayOfWeek == System.DayOfWeek.Sunday)
{
yield return DatMonth;
}
DatMonth = DatMonth.AddDays(1.0);
}
}
我很想把你的函数重写为像这样的扩展名
public static IEnumerable<Datetime> DaysOfMonth(
this DateTime any,
DayOfWeek day)
{
// start at first of month
var candidate = new DateTime(any.Year, any.Month, 1);
var offset = (int)day - (int)candidate.DayOfWeek;
if (offset < 0)
{
offset += 7
}
candidate = candidate.AddDays(offset);
while (cadidate.Month == any.Month)
{
yield return candidate;
candidate = candidate.AddDays(7.0)
}
}
然后你可以像这样使用它
var allSundaysInMonth = DateTime.Now.DaysOfMonth(DayOfWeek.Sunday);
如果您想将IEnumerable<DateTime>
转换为string
,可以执行此操作,
var listOfDates = string.Join<DateTime>(", ", allSundaysInMonth);
使用this string.Join
重载
如果你真的希望这些日子为DateTime[]
你可以做到这一点(但没有必要)
DateTime[] allSundaysInMonth = GetDatesOfSundays(DateTime.Now).ToArray();
或我的扩展示例
var allSundaysInMonth = DateTime.Now.DaysOfMonth(DayOfWeek.Sunday).ToArray();
答案 1 :(得分:0)
您可以选择DateTime[]
或IEnumerable<DateTime>
。
您的方法签名应为
private IEnumerable<DateTime> GetDatesOfSundays(DateTime DatMonth)
或
private DateTime[] GetDatesOfSundays(DateTime DatMonth)
如果您没有使用IEnumerable
,请选择
private DateTime[] GetDatesOfSundays(DateTime DatMonth)
{
List<DateTime> lst = new List<DateTime>();
DatMonth = DatMonth.AddDays(-DatMonth.Day + 1);
DateTime DatMonth2 = DatMonth.AddMonths(1).AddDays(System.Convert.ToDouble(-1));
while (DatMonth < DatMonth2)
{
if (DatMonth.DayOfWeek == System.DayOfWeek.Sunday)
{
lst.Add(DatMonth);
DatMonth = DatMonth.AddDays(7);
continue;
}
DatMonth = DatMonth.AddDays(1);
}
return lst.ToArray();
}
并将其命名为
DateTime[] allSundaysInMonth = GetDatesOfSundays(System.DateTime.Now);