Search code examples
asp.net-mvcdatetimerazortostring

How to get the month abbreviation instead of number in Razor syntax


I have the following code in my MVC 4 razor view, which is supposed to take the DateTime property called modifiedDate, and print out the month name, i.e., Jan, Feb, etc., instead of 1, 2.

@foreach (var post in Model.NewsList)
{
   <li class="entry">
     <p class="calendar"><em>@post.modifiedDate.Value.Month.ToString("mmm")</em></p>               
   </li>
}

Any ideas how to do this?


Solution

  • See The "MMMM" Custom Format Specifier

    Usage:

    DateTime? date = DateTime.Now;
    
    date.Value.ToString("MMMM"); // Prints the Month name (e.g. May)
    

    Corrected:

    @foreach (var post in Model.NewsList)
    {
       <li class="entry">
         <p class="calendar"><em>@post.modifiedDate.Value.ToString("MMMM")</em></p>               
       </li>
    }