-2

When it's being displayed in the the View's datagrid, the dates are shown like 10/20/2016 12:00:00 AM. Can I remove the time using the LINQ in my Controller? I tried converting it to string using different techniques but to no success.

Model

public class UserModel
{
    public string userid { get; set; }
    public string userdesc { get; set; }
    public DateTime startdt { get; set; }
    public DateTime enddt { get; set; }
    public string status { get; set; }
}

Controller

var users = from u in _odb.USR_MSTR
            select new UserModel
            {
                userid = u.USR_ID,
                userdesc = u.USR_DESC,
                startdt = u.STRT_DT, //Can I get the date only from this dates?
                enddt = u.END_DT,
                status = (u.INACTV_DT == null ? "Active" : "Inactive")
            };

View

<tbody id="dbBody">
    @foreach (var item in Model)
    {
        <tr>
            <td class="hidden">
                @Html.DisplayFor(modelItem => item.startdate)
            </td>
            <td class="hidden">
                @Html.DisplayFor(modelItem => item.enddate.ToShortDateString())
            </td>
        </tr>
    }
</tbody>
5
  • 1
    If you don't want to display the time then you need to change the code that displays it, not the code that gets it from the DB. Commented Oct 12, 2016 at 12:26
  • @BviLLe_Kid That will just truncate the time portion to be midnight and the resulting DateTime will still have a time portion. This is a display issue, not a retrieval issue. Commented Oct 12, 2016 at 12:30
  • @HarambeAttackHelicopter: I hope you're not storing strings instead of datetimes in your database, can you show the query? Commented Oct 12, 2016 at 12:33
  • 2
    That's because UserModel.startdt is a DateTime and not a string. Do formatting stuff in your view, not in your model. Commented Oct 12, 2016 at 12:35
  • 1
    @TimSchmelter It's likely that the view is setup for DateTime and not string and the OP needs to do the formatting in the view instead of the controller or maybe use attributes as in the duplicate. Commented Oct 12, 2016 at 12:36

1 Answer 1

1

If you want to suppress the displayed time you have to add DisplayFormat attributes to your Model

public class UserModel
{
    public string userid { get; set; }
    public string userdesc { get; set; }

    [DisplayFormat(DataFormatString = "{0:d}")]
    public DateTime startdt { get; set; }

    [DisplayFormat(DataFormatString = "{0:d}")]
    public DateTime enddt { get; set; }

    public string status { get; set; }
}

or format the date in the view

@foreach (UserModel item in Model)
{
     @string.Format("{0:d}", item.startdt) 
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.