How do I format a DateTime to be displayed as simp

2019-07-23 03:09发布

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

2条回答
可以哭但决不认输i
2楼-- · 2019-07-23 03:34

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

查看更多
戒情不戒烟
3楼-- · 2019-07-23 03:43

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);
查看更多
登录 后发表回答