简体   繁体   中英

compare date from DBfield with current date

I'm new to the .NET world, so pardon my newbie question.

I'm building a webapp which gets data from a database. I am using Entity Framework, database first approach. I want to compare a date field from the database with the current date. If there's 20 or less days remaining til the current date, i want it to be shown in my view. If there's more that 20 days remaining, it should not be shown in my view. Right now i am presenting everything.

Controller:

        [StandardUserAuthorize]
    public ActionResult Index()
    {
        var model = new HomeVM
        {
            Offerter = db.AH_AVTAL_HUVUD.ToList(),
            Kallelser = db.AS_AVTAL_SCHEMA.ToList()
            //This is where the datefield is, in Kallelser.


        };
        return View(model);
    }

ViewModel:

    public class HomeVM
{
    public IEnumerable<AH_AVTAL_HUVUD> Offerter { get; set; }
    public IEnumerable<AS_AVTAL_SCHEMA> Kallelser { get; set; }
}

View:

 @foreach (var item in Model.Kallelser)
                    {
                        <tr>
                            <td>
                                @Html.DisplayFor(modelItem => item.AS_SC_DAT)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.AS_SC_VECKA)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.AS_SC_OP_TXT)
                            </td>
                        </tr>
                    }

How can i do this kind of logic? And where? I assume the it should be done in the controller.

Best Regards.

I Hope I Fully Understood You

//this is the after 20 days
 var ComparingDay = DateTime.Now.AddDays(20);

//this linq expression to get days between today and the comparing day
var ListOfNextDays = YouContextClass.YourDBSet.Where(D => D.Date > DateTime.Now && D.Date < ComparingDay).ToList();

Now You Have List Of Days That You Can Pass To You View

if you want the other days that dosn't match your condition u can use the except operator

I assume you wrote a sql somewhere in your application. Just add a where clause to it to retrieve only those you want to show.

SELECT t.*
FROM   Table t
WHERE  DATEDIFF(DAY, t.Date, GETDATE()) <= 20

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