将日期格式化为仅包含月份和年份 - "MMM-yyyy"

6

我正在使用MVC 4.0 / C# / Razor视图开发。在模型中,我有一个日期

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

在 View 中,我正在使用以下方式获取日期:

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

结果中我得到的日期格式为“2015年5月12日”。我想跳过这个日期,并得到“2015年5月”的格式。

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


1
只需删除“dd-”,并使用“[DisplayFormat(DataFormatString = "{0:MMM-yyyy}")]”。 - user3559349
@StephenMuecke - 应该在回答中,而不是评论中。 - VulgarBinary
@irfi - 欢迎来到StackOverflow!既然这是您的第一个问题,我鼓励您阅读http://stackoverflow.com/help/someone-answers。祝你好运并欢迎! - VulgarBinary
1
我要删除我的回答,因为从技术上讲,正如@VulgarBinary所说,在DisplayFor中它不起作用,但在TextBoxFor中相同的方法可以使用。由于疏忽,我错过了那一部分!! :) 而且第一个格式,正如VulgarBinary已经回答的那样,我认为这里不需要再提了.. :) - Guruprasad J Rao
3个回答

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

关于在C#中格式化日期的更多信息可以在MSDN这里找到。

另外还有一种使用自定义编辑模板的选项,您可以阅读这篇stackoverflow文章了解更多细节:ASP.NET MVC 4基本类型编辑模板


4
您可以按照以下方式在View文件中格式化日期:

您可以按照以下方式在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; }

@Convert.ToDateTime(...)放在视图中是不好的做法。 ViewModel 应该具有所需数据类型的字段。如果它是日期并且您正在使用注释,则只需执行@Html.DisplayFor(x => x.EffectiveDate)而不是您发布的内容。[Display(...)]的复制和粘贴令人印象深刻,我无法想象您花了多长时间来作为答案的一部分。 - VulgarBinary

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

例如 = "2020年7月"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接