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>
Currently, the format is "10/31/2014 12:00:00 AM"
I would prefer this to simply be Oct 31
which I believe is the MMM d
format.
Is something like this possible?
var myDate = event["DisplayDate"];
var oldFormat = "M/d/yyyy h:m:s";
var newFormat = "MMM d";
var newDate = myDate.oldFormat.ConvertTo(newFormat);
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
?
You need to parse it, which results in a DateTime, which you can then format any way you want using
.ToString()
You should be able to simply use Razor to call a conversion:
Another approach:
You could also do,
DateTime.ParseExact
.Another option, hope this helps.
If you have a DateTime object, you can use it that way :
(btw, I don't know if "MMM d" is a valid format)
(btw2, using var to declare all your variables is a bad habit. It's easier to read code where you know the type of the variable without having to look at the return of the function to know the type of the variable you're using.)