开发者

How to suppress time part of a .NET DateTime in display if and only if time part = 00:00:00?

In an ASP.NET page I have this:

<asp:Label ID="MyDateTimeLabel" runat="server" 
     Text='<%# Eval("MyDateTime") %>' />

I'd like to have it formatted like

... Eval("开发者_运维问答MyDateTime", "{0:d}") ... // Display only the date

if and only if the time part of MyDateTime is 00:00:00. Otherwise like this:

... Eval("MyDateTime", "{0:g}") ... // Display date and time in hh:mm format

Is this possible and how can I do that?

Thank you for hints in advance!


I'd put this in my code-behind:

// This could use a better name!
protected string FormatDateHideMidnight(DateTime dateTime) {
    if (dateTime.TimeOfDay == TimeSpan.Zero) {
        return dateTime.ToString("d");
    } else {
        return dateTime.ToString("g");
    }
}

And change the .aspx to call that:

<asp:Label ID="MyDateTimeLabel" runat="server" 
     Text='<%# FormatDateHideMidnight((DateTime)Eval("MyDateTime")) %>' />

If you do this in multiple places, consider writing an extension method for DateTime and put this logic there (perhaps with additional parameters to supply different formats, etc.).


You did not mention which .net language you use. With VB.NET, you can use the following inline expression:

... Text='<%# Eval("MyDateTime", If(Eval("MyDateTime").TimeOfDay = TimeSpan.Zero, "{0:d}", "{0:g}")) %>'

I did not test with C#, but I guess replacing If(...) with the ternary ?: operator and casting the result of Eval to a DateTime before accessing TimeOfDay should do the trick.


didn't test, but off the top of my head:

in markup

<asp:Label ID="MyDateTimeLabel" runat="server" 
     Text='<%# FormatMyDateTime((DateTime)Eval("MyDateTime")) %>' />

in code-behind:

protected string FormatMyDateTime(DateTime date)
{
      // Do your if else for formatting here.
}


You can substitute the following code in the aspx file or create a method and call the method to return the value.

<%
   DateTime dtTime = DateTime.Now;

    if (dtTime.TimeOfDay == TimeSpan.Zero)
        Response.Write(String.Format("{0:d}", dtTime));
    else
        Response.Write(String.Format("{0:g}", dtTime));
%>


To show only date part

<asp:Label id="lblExamDate" runat="server" Text='<%#Convert.ToDateTime(Eval("theExamDate.Date")).ToShortDateString()%>'></asp:Label>

and to show only time part

<asp:Label ID="lblStartTime" runat="server" Text='<%#Convert.ToDateTime(Eval("ExamStartTime")).ToShortTimeString()%>' />


I am not sure if you are looking for this, but I feel it's worth trying. Hope it works.

<%# String.Format(Eval("MyDateTime"),"{0:d}") %>

<%# String.Format(Eval("MyDateTime"),"{0:g}") %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜