Samantha J T Star
Samantha J T Star

Reputation: 32798

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?

Upvotes: 17

Views: 93608

Answers (7)

GJKH
GJKH

Reputation: 1725

In the interest of completeness, you could also use string interpolation. I don't think this was an available feature when this question was asked.

@($"{crd:dd/mm/yyyy HH:mm}")

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated

Upvotes: 0

Cagdas Bsn
Cagdas Bsn

Reputation: 36

Try Razor View

@Html.Raw(item.Today_Date.Date.ToString("dd.MM.yyyy"))

Upvotes: 2

JoshYates1980
JoshYates1980

Reputation: 3626

If you have a list of dates and want to grab the first:

Begin Date: @string.Format("{0:MM/dd/yyyy}", Convert.ToDateTime(Model.aList.Where(z => z.Counter == 1).Select(z => z.Begin_date).First()))

Upvotes: -2

user4439128
user4439128

Reputation: 49

Use this code to format your date:

@string.Format("{0:ddd}",Convert.ToDateTime(Html.DisplayFor(model => model.Booking.BookingFromDate).ToString()))

If your date field with required attribute then you don't want to validate null value. Other wise you can use ternary operator

Upvotes: 5

Ravi Ram
Ravi Ram

Reputation: 24488

How about

@crd.ToShortDateString()

Upvotes: 4

JustinStolle
JustinStolle

Reputation: 4420

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

Upvotes: 29

Damith
Damith

Reputation: 63065

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

[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
pubilc DateTime CreationDate{ get; set }

Upvotes: 19

Related Questions