简体   繁体   中英

How do I parse date and time from timestamp in view file(.cshtml) in asp.net mvc?

I thought it is simple thing but googling and researching for more than 2 hours still could not find answer. I have my timestamp (datatype is DateTime) in the model @item.arrival. And I have 2 columns in my web app where I have to separate date and time from the field @item.arrival and display it. I can access the field like this in my view file

<td>@item.arrival</td>
<td>@item.arrival</td>

But I don't how to separate date and time. The closest I got was separating using the html helper

<td>@Html.TextBoxFor(modelItem => item.arrival, "{0:dd/MM/yyyy}")</td>

But above code puts txt box in my page and I don't want that, I have my own styling in my page where i want to display my date and time in separate places. Any guidance is appreciated.

I am using asp.net mvc c# and I want to do this parsing in view and not in my controller.

Let say your Nullable property is defined like this

 public DateTime? arrival { get { return DateTime.Now; } }

.cshtml

<td>@item.arrival.Date.ToString("d")</td> //3/19/2020
<td>@item.arrival.ToString("HH:mm")</td> //23:15

Update for handling Nullable, just add ? after the type

<td>@item.arrival?.Date.ToString("d")</td> 
//If arrival is null it returns null else it will return Date

@item.arrival.Value.ToString("yyyy-MM-dd") I have to use "value" inbetween since it is nullable datetime. Thank you everyone for the help. Much appreciate it.

Use Below code

<td>@item.arrival.ToString("dd-MMM-yyyy")</td>
<td>@item.arrival.ToString("hh:mm tt")</td>

Refer: https://docs.microsoft.com/en-us/dotnet/api/system.datetime.tostring?view=netframework-4.8

Hope this will helps 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