Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format Date to only Month and Year - "MMM-yyyy"

I am working on MVC 4.0./C#/Razor view. In model I have a date

[Display(Name = "For Period")]
[DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}")] 
public System.DateTime ForPeriod { get; set; }

and in View I am getting date using

@Html.DisplayFor(modelItem => item.ForPeriod)

and in result I am getting date in "12-May-2015" format. I want to skip the day from this date and in result I want "May-2015".

My question is what should I used in View to get this "MMM-yyyy" format?

like image 280
Irfan Ahmed Avatar asked May 14 '15 05:05

Irfan Ahmed


People also ask

How do I format date only month and year?

If you only want to display a date with the year and month, you can simply apply the custom number format "yyyymm" to the date(s). This will cause Excel to display the year and month together, but will not change the underlying date.

How do you make a date only show as month and year in Excel?

Select the cells you want to format. Press CTRL+1. In the Format Cells box, click the Number tab. In the Category list, click Date, and then choose a date format you want in Type.

How do you format a date in MMM YYYY?

First, pick the cells that contain dates, then right-click and select Format Cells. Select Custom in the Number Tab, then type 'dd-mmm-yyyy' in the Type text box, then click okay.


2 Answers

[Display(Name = "For Period")]
[DisplayFormat(DataFormatString = "{0:MMM-yyyy}")] 
public System.DateTime ForPeriod { get; set; }

More information on formatting dates in C# can be found on MSDN here.

There is an additional option of using a custom editor template which you can read this article on stack overflow for more details - ASP.NET MVC 4 Editor Template for basic types

like image 74
VulgarBinary Avatar answered Sep 21 '22 16:09

VulgarBinary


You can format date in View file by following way

<span>@Convert.ToDateTime(item.EffectiveDate).ToString("MMM-yyyy")</span>

For can also format date from model

[Display(Name = "For Period")]
[DisplayFormat(DataFormatString = "{0:MMM-yyyy}")] 
public System.DateTime ForPeriod { get; set; }
like image 45
Muhammad Tariq Siddiqui Avatar answered Sep 20 '22 16:09

Muhammad Tariq Siddiqui