Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display only DATE part on View in ASP.NET MVC

I'm trying to display only date part on my view, value I'm getting from database is pretty big and I really don't need informations like hrs, mns, seconds etc, I'm only interested in date, for example I would like to display only :

17/04/2017 

And this is what I've tried so far:

<td>
       @Html.DisplayFor(modelItem => ((DateTime)item.ValidFrom).ToString("dd/MM/yyyy"))
</td>
<td>
       @Html.DisplayFor(modelItem => ((DateTime)item.ValidTo).ToString("dd/MM/yyyy"))
</td>

Here is the DateType of my Properties:

public System.DateTime ValidFrom { get; set; }
public Nullable<System.DateTime> ValidTo { get; set;

And here is the issue I get: [![enter image description here][1]][1]

like image 308
Roxy'Pro Avatar asked Jan 30 '26 12:01

Roxy'Pro


1 Answers

Just Output Directly

Instead of using the DisplayFor() helper method, you might consider just outputting the values directly if that would work for you:

<td>
   @modelItem.ValidFrom.ToString("dd/MM/yyyy")
</td>
<td>
   @modelItem.ValidTo?.ToString("dd/MM/yyyy")
</td>

Consider ViewModel-Level Formatting

Another possibly better option, would be performing this within your ViewModel itself as opposed to within the View:

public System.DateTime ValidFrom { get; set; }
public Nullable<System.DateTime> ValidTo { get; set; }

// These will be formatted versions of the properties specifically for output
public string FormattedFrom => ValidFrom.ToString("dd/MM/yyyy");
public string FormattedTo => ValidTo?.ToString("dd/MM/yyyy") ?? "Present";

And then simply use those properties instead:

<td>
   @Model.FormattedFrom
</td>

<td>
   @Model.FormattedTo
</td>
like image 159
Rion Williams Avatar answered Feb 02 '26 00:02

Rion Williams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!