Convert string to custom date format - c# razor

2019-07-27 09:58发布

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?

标签: c# razor
3条回答
地球回转人心会变
2楼-- · 2019-07-27 10:18

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);
查看更多
干净又极端
3楼-- · 2019-07-27 10:26

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.

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-07-27 10:36

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

查看更多
登录 后发表回答