格式日期只有月份和年份 - “MMM-yyyy”

时间:2015-05-14 05:20:12

标签: asp.net-mvc datetime

我正在研究MVC 4.0./C#/Razor视图。在模型中我有一个日期

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

在视图中我使用

获取日期
@Html.DisplayFor(modelItem => item.ForPeriod)

结果我得到了“2015年5月12日”格式的约会。我想从这个日期跳过这一天,结果我想要“2015年5月”。

我的问题是我应该在View中使用什么来获得这种“MMM-yyyy”格式?

3 个答案:

答案 0 :(得分:4)

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

有关格式化日期的更多信息,请参阅on MSDN here.

还有一个使用自定义编辑器模板的附加选项,您可以在堆栈溢出中阅读本文以获取更多详细信息 - ASP.NET MVC 4 Editor Template for basic types

答案 1 :(得分:3)

您可以按照以下方式在View文件中设置日期格式

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

也可以从模型

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

答案 2 :(得分:0)

在ASP.NET中将当前日期转换为年月格式的代码

案例-1

Dim Current_Date as String = DateAndTime.Now.ToString("dd/MM/yyyy")

msgbox(Current_Date) //THIS WILL DISPLAY CURRENT DATE IN SHORT STRING FORMAT

例如= = "05/07/2020"

案例-2

Dim Current_Date as String = DateAndTime.Now.ToString("MMMM-yyyy")

msgbox(Current_Date) //THIS WILL DISPLAY CURRENT MONTH & YEAR

例如= = "July-2020"

相关问题