我想提取当月的所有星期日,并拥有以下代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
问题在于我的所有类型字符串for allSundaysInMonth,也是空的.sReturn是字符串类型,但我再次传递一个日期(我知道:))但是allSundaysInMonth应该是什么类型?sReturn确实有正确的日期...我需要在控制器视图的下拉列表中显示这些日期,以便用户可以选择他/她需要为其运行报告的任何星期日.
谢谢
怎么样
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我很想把你的函数重写为这样的扩展
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)
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用它
var allSundaysInMonth = DateTime.Now.DaysOfMonth(DayOfWeek.Sunday);
Run Code Online (Sandbox Code Playgroud)
如果你想将IEnumerable<DateTime>a 转换成a,string你可以这样做,
var listOfDates = string.Join<DateTime>(", ", allSundaysInMonth);
Run Code Online (Sandbox Code Playgroud)
使用这个 string.Join重载
如果你真的想要这样的日子DateTime[]你可以做到这一点(但没有必要)
DateTime[] allSundaysInMonth = GetDatesOfSundays(DateTime.Now).ToArray();
Run Code Online (Sandbox Code Playgroud)
或者我的扩展示例
var allSundaysInMonth = DateTime.Now.DaysOfMonth(DayOfWeek.Sunday).ToArray();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
94 次 |
| 最近记录: |