How do I format a DateTime to be displayed as simp

2019-07-23 03:01发布

问题:

I am supplying a full DateTime located at model.StartDate in the following code:

@Html.DisplayFor(model => model.StartDate.ToString("hh:mm tt"),
CultureInfo.CreateSpecificCulture("hu-HU"));

My goal is to take the full DateTime

8/30/2012 11:33:48 AM

and display only

11:33:48 AM

however, I get the following error:

Templates can be used only with field access, property access,
single-dimension array index, or single-parameter custom indexer expressions.

Why is this error happening?


Note: I referenced this documentation to format my .ToString for my DateTime: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

回答1:

You can put a DataAnnotation on your model class. Something like this -> [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)].



回答2:

Create a new property on your model that returns the formatted date.

public class MyModel
{
    // Other fields including your current StartDate

    public class StartDateFormatted
    {
        get 
        { 
            return StartDate.ToString("hh:mm tt"), 
               CultureInfo.CreateSpecificCulture("hu-HU"));
        }
    }
}

Then use that property in your Razor markup

@Html.DisplayFor(model => model.StartDateFormatted);