Convert string to custom date format - c# razor

2019-07-27 09:50发布

问题:

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?

回答1:

You should be able to simply use Razor to call a conversion:

@item.Date.ToString("MMMM dd, yyyy")

Another approach:

[DisplayFormat(DataFormatString = "{MMMM 0:dd yyyy")]
public DateTime Date { get; set; }
@Html.DisplayFor(d => d.Date);

You could also do, DateTime.ParseExact.

var date = DateTime.ParseExact(oDate, format, CultureInfo.InvariantCulture);

Another option, hope this helps.



回答2:

If you have a DateTime object, you can use it that way :

 DateTime myDate = .... ;
 string dateToDisplay = myDate.ToString(newFormat);

(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.)



回答3:

You need to parse it, which results in a DateTime, which you can then format any way you want using .ToString()

var dateTime = DateTime.ParseExact(myDate, oldFormat, CultureInfo.InvariantCulture);
var newDate = dateTime.ToString(newFormat);


标签: c# razor