将字符串转换为自定义日期格式 - C# razor [英] Convert string to custom date format - c# razor
问题描述
我有一个存储事件的 mySQL 数据库,这些事件都有日期.我正在提取事件日期,它们在 HTML 中作为字符串输出.
I have a mySQL database that is storing events and those events all have dates. I'm pulling in the event dates and they're outputting in the HTML as strings.
<ul id="latest-events">
@{
IEntity[] latestEvents = ViewBag.LatestEvents;
foreach (IEntity event in latestEvents)
{
<li class="item">
<span class="event-date">
@event["DisplayDate"]
</span>
<a href="#">@event["Title"]</a>
<span class="teaser">@Html.Raw(event["Teaser"])</span>
</li>
}
}
</ul>
目前格式为10/31/2014 12:00:00 AM"
我希望这只是 Oct 31
,我认为这是 MMM d
格式.
I would prefer this to simply be Oct 31
which I believe is the MMM d
format.
这样的事情有可能吗?
var myDate = event["DisplayDate"];
var oldFormat = "M/d/yyyy h:m:s";
var newFormat = "MMM d";
var newDate = myDate.oldFormat.ConvertTo(newFormat);
明确地说,我不知道 C#,这就是为什么上面的 ConvertTo
甚至可能是不可能的.是否可以使用 DateTime
转换我的字符串?
Just to be clear, I don't know C# which is why the above ConvertTo
is probably not even possible. Is it possible to convert my string using DateTime
?
推荐答案
您应该能够简单地使用 Razor 来调用转换:
You should be able to simply use Razor to call a conversion:
@item.Date.ToString("MMMM dd, yyyy")
另一种方法:
[DisplayFormat(DataFormatString = "{MMMM 0:dd yyyy")]
public DateTime Date { get; set; }
@Html.DisplayFor(d => d.Date);
你也可以这样做,DateTime.ParseExact
.
var date = DateTime.ParseExact(oDate, format, CultureInfo.InvariantCulture);
另一种选择,希望对您有所帮助.
Another option, hope this helps.
这篇关于将字符串转换为自定义日期格式 - C# razor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!