简体   繁体   English

如何 asp.net MVC 所有日期之间的两个日期

[英]How To asp.net MVC Two dates between All Dates

I have two date example 12.1.2019 12.2.2019我有两个日期示例 12.1.2019 12.2.2019

 public class DatelistController : Controller
{

    [HttpGet]

    public ActionResult Index()
    {

       DateTime start = new DateTime(2012, 2, 1);
        DateTime end = new DateTime(2012, 3, 1); ;
        var dates = new List<DateTime>();

        for (var dt = start; dt <= end; dt = dt.AddDays(1))
        {
            dates.Add(dt);
        }
        Enumerable.Range(0, 1 + end.Subtract(start).Days)
         .Select(offset => start.AddDays(offset))
        .ToArray();
        ViewData["AllDate"] = new SelectList(dates);
        return View();
    }

Index指数

> @foreach (var item in ViewData["AllDate"] as List<DateTime>)
{
    <tr> 
    <td style="font-family:Verdana; font-size:12px;">@item</td>
        </tr>
        }

I can't Index page there are no structures that I built.我无法索引页面没有我构建的结构。

What i want to do it;我想做什么;

Select Start Date and End Date is two date between get All Date's then later I will put the value on the days obtained using the check box Select 开始日期和结束日期是获取所有日期之间的两个日期,然后我将把值放在使用复选框获得的天数上

I would be happy if you help Thank you!如果你能帮助我会很高兴谢谢你!

You are doing it wrong.你这样做是不对的。 Comparing two Day will give you the wrong value.比较Day会给你错误的价值。 For example, You are comparing 11 of 11 Jan and 11 February and it will give you 0, but it is not.例如,您正在比较 1 月 11 日和 2 月 11 日的 11,它会给您 0,但事实并非如此。

Do like this.这样做。

DateTime start;
DateTime end;
var dates = new List<DateTime>();

for (var dt = start; dt <= end; dt = dt.AddDays(1))
{
    dates.Add(dt);
}

You can also use LINQ as explained here .您也可以使用 LINQ ,如此所述。

Enumerable.Range(0, 1 + end.Subtract(start).Days)
          .Select(offset => start.AddDays(offset))
          .ToArray(); 

view error= System.NullReferenceException: (... as System.Collections.Generic.List<System.DateTime>) returned null.查看错误= System.NullReferenceException: (... as System.Collections.Generic.List<System.DateTime>) returned null. Thank you谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM