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

On an ASP.NET page, I have the following:

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

I would like to format it as

... Eval("MyDateTime", "{0:d}") ... // Display only the date

if and only if the temporary part of MyDateTime is 00:00:00. Otherwise:

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

Is it possible and how can I do it?

Thanks for the tips in advance!

+3
source share
6 answers

I would put this in my code:

// 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 modify .aspx to call this:

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

, , DateTime (, ..).

+6

, :

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

:

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

, .net . VB.NET :

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

#, , , If(...) ?: Eval DateTime, TimeOfDay .

+1

, , , . , .

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

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

You can replace the following code in an 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));
%>
0
source

Show only part of the date

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

and show only the temporary part

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

Source: https://habr.com/ru/post/1733536/


All Articles