Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I format a DateTime in a Razor view?

I have variables like:

DateTime crd = a.CreationDate; (shown as a variable in C# but available in razor views)

I want to show these as a date using the format: 11/06/2011 02:11

Ideally I would like to have some kind of HTML helper for this. Anyone out there already have something that might meet my needs?

like image 670
Samantha J T Star Avatar asked Nov 06 '11 09:11

Samantha J T Star


People also ask

How do you format a DateTime?

yyyy-M-d — Example: 2013-6-23. M/d/yyyy — Example: 6/23/2013. d/M/yyyy — Example: 23/6/2013. dd.

How do I get only the date from DateTime in razor?

Format({"0:dd/MM/yyyy"}, @Model. FromDate);


2 Answers

You could create a Display Template or Editor Template like in this answer, but the format would apply to all DateTime variables in the given scope (maybe good or bad).

Using the DisplayFormat attribute works well to define formats for individual fields.

Remember to use @Html.DisplayFor(model=>model.crd) and/or @Html.EditorFor(model=>model.crd) syntax for either of the above.

You can always use the DateTime.ToString() method in your views as well for more ad hoc formatting.

@crd.ToString("MM/dd/yyyy HH:mm") // time using a 24-hour clock
like image 155
JustinStolle Avatar answered Sep 21 '22 08:09

JustinStolle


in your model you can set [DisplayFormat] attribute with formatting as you wish

[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
pubilc DateTime CreationDate{ get; set }
like image 44
Damith Avatar answered Sep 20 '22 08:09

Damith