简体   繁体   English

将字符串转换为自定义日期格式-C#Razor

[英]Convert string to custom date format - c# razor

I have a mySQL database that is storing events and those events all have dates. 我有一个存储事件的mySQL数据库,这些事件都有日期。 I'm pulling in the event dates and they're outputting in the HTML as strings. 我输入事件日期,它们以字符串形式在HTML中输出。

<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" 当前,格式为"10/31/2014 12:00:00 AM"

I would prefer this to simply be Oct 31 which I believe is the MMM d format. 我希望这只是Oct 31 ,我相信是MMM d格式。

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. 只是要清楚一点,我不知道C#,这就是为什么上面的ConvertTo甚至不可能的原因。 Is it possible to convert my string using DateTime ? 是否可以使用DateTime转换我的字符串?

You should be able to simply use Razor to call a conversion: 您应该能够简单地使用Razor来调用转换:

@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 . 您也可以做DateTime.ParseExact

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

Another option, hope this helps. 另一个选择,希望对您有所帮助。

If you have a DateTime object, you can use it that way : 如果您有DateTime对象,则可以通过以下方式使用它:

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

(btw, I don't know if "MMM d" is a valid format) (顺便说一句,我不知道“ MMM d”是否是有效格式)
(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.) (btw2,使用var声明所有变量是一个坏习惯。在您知道变量类型的地方,更容易阅读代码,而不必查看函数的返回值即可知道所使用的变量的类型。 )

You need to parse it, which results in a DateTime, which you can then format any way you want using .ToString() 您需要对其进行解析,从而产生一个DateTime,然后您可以使用.ToString()格式化任何所需的格式

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM