简体   繁体   中英

How To asp.net MVC Two dates between All Dates

I have two date example 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

I would be happy if you help Thank you!

You are doing it wrong. Comparing two Day will give you the wrong value. For example, You are comparing 11 of 11 Jan and 11 February and it will give you 0, but it is not.

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 .

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. Thank you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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