[asp.net] How to render a DateTime in a specific format in ASP.NET MVC 3?

If I have in my model class a property of type DateTime how can I render it in a specific format - for example in the format which ToLongDateString() returns?

I have tried this...

@Html.DisplayFor(modelItem => item.MyDateTime.ToLongDateString())

...which throws an exception because the expression must point to a property or field. And this...

@{var val = item.MyDateTime.ToLongDateString();
  Html.DisplayFor(modelItem => val);
}

...which doesn't throw an exception, but the rendered output is empty (although val contains the expected value, as I could see in the debugger).

Thanks for tips in advance!

Edit

ToLongDateString is only an example. What I actually want to use instead of ToLongDateString is a custom extension method of DateTime and DateTime?:

public static string FormatDateTimeHideMidNight(this DateTime dateTime)
{
    if (dateTime.TimeOfDay == TimeSpan.Zero)
        return dateTime.ToString("d");
    else
        return dateTime.ToString("g");
}

public static string FormatDateTimeHideMidNight(this DateTime? dateTime)
{
    if (dateTime.HasValue)
        return dateTime.Value.FormatDateTimeHideMidNight();
    else
        return "";
}

So, I think I cannot use the DisplayFormat attribute and DataFormatString parameter on the ViewModel properties.

This question is related to asp.net asp.net-mvc asp.net-mvc-3

The answer is


you can do like this @item.Date.Value.Tostring("dd-MMM-yy");


In MVC5 I'd use, if your model is the datetime

string dt = Model.ToString("dd/MM/yyy"); 

Or if your model contains the property of the datetime

string dt = Model.dateinModel.ToString("dd/MM/yyy"); 

Here's the official meaning of the Formats:

https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx


this will display in dd/MM/yyyy format in your View

In View:

instead of DisplayFor use this code

<td>

@(item.Startdate.HasValue ? item.Startdate.Value.ToString("dd/MM/yyyy") : "Date is Empty")

</td

it also checks if the value is null in date column, if true then it will display Date is Empty or the actual formatted date from the column.

Hope helps someone.


Only View File Adjust like this. You may try this.

@Html.FormatValue( (object)Convert.ChangeType(item.transdate, typeof(object)), 
                            "{0: yyyy-MM-dd}")

item.transdate it is your DateTime type data.


Simple formatted output inside of the model

@String.Format("{0:d}", model.CreatedOn)

or in the foreach loop

@String.Format("{0:d}", item.CreatedOn)

I use the following approach to inline format and display a date property from the model.

@Html.ValueFor(model => model.MyDateTime, "{0:dd/MM/yyyy}")

Otherwise when populating a TextBox or Editor you could do like @Darin suggested, decorated the attribute with a [DisplayFormat] attribute.


My preference is to keep the formatting details with the view and not the viewmodel. So in MVC4/Razor:

@Html.TextBoxFor(model => model.DateTime, "{0:d}");

datetime format reference: http://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.71).aspx

Then I have a JQuery datepicker bound to it, and that put's the date in as a different format...doh!

Looks like I need to set the datepicker's format to the same formatting.

So I'm storing the System.Globalization formatting in a data-* attribute and collecting it when setting up the

@Html.TextBoxFor(
    model => model.DateTime.Date, 
    "{0:d}", 
    new 
    { 
        @class = "datePicker", 
        @data_date_format=System.Globalization.CultureInfo
                          .CurrentUICulture.DateTimeFormat.ShortDatePattern 
    }));

And here's the sucky part: the formats of .net and datepicker do not match, so hackery is needed:

$('.datePicker').each(function(){
    $(this).datepicker({
        dateFormat:$(this).data("dateFormat").toLowerCase().replace("yyyy","yy")
    });
});

that's kind of weak, but should cover a lot of cases.


If all your DateTime types are rendered the same way you can use a custom DateTime display template.

In your Views folder create a folder named "DisplayTemplates" either under your controller specific views folder, or under "Shared" folder (these work similar to partials).

Inside create a file named DateTime.cshtml that takes DateTime as the @model and code how you want to render your date:

@model System.DateTime
@Model.ToLongDateString()

Now you can just use this in your views and it should work:

@Html.DisplayFor(mod => mod.MyDateTime)

As long as you follow the convention of adding it to the "DisplayTemplates" folder and naming the file to match the type your are displaying, MVC will automatically use that to display your values. This also works for editing scenarios using "EditorTemplates".

Here's some more information on templates.


if I just want to display the date in short format I just use @Model.date.ToShortDateString() and it prints the date in


If all you want to do is display the date with a specific format, just call:

@Model.LeadDate.ToString("dd-MMM-yyyy")

@Model.LeadDate.ToString("MM/dd/yy")

It will result in following format,

26-Apr-2013

04/26/13

works for me

<%=Model.MyDateTime.ToString("dd-MMM-yyyy")%>

You could decorate your view model property with the [DisplayFormat] attribute:

[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", 
               ApplyFormatInEditMode = true)]
public DateTime MyDateTime { get; set; }

and in your view:

@Html.EditorFor(x => x.MyDate)

or, for displaying the value,

@Html.DisplayFor(x => x.MyDate)

Another possibility, which I don't recommend, is to use a weakly typed helper:

@Html.TextBox("MyDate", Model.MyDate.ToLongDateString())

Had the same problem recently.

I discovered that simply defining DataType as Date in the model works as well (using Code First approach)

[DataType(DataType.Date)]
public DateTime Added { get; set; }

@{
  string datein = Convert.ToDateTime(item.InDate).ToString("dd/MM/yyyy");        
  @datein
}

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to asp.net-mvc-3

Better solution without exluding fields from Binding IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication” Can we pass model as a parameter in RedirectToAction? return error message with actionResult Why is this error, 'Sequence contains no elements', happening? Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function 500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid String MinLength and MaxLength validation don't work (asp.net mvc) How to set the value of a hidden field from a controller in mvc How to set a CheckBox by default Checked in ASP.Net MVC