Format date in Table Display

Stacey Fontenot
Stacey Fontenot used Ask the Experts™
on
I have an MVC Web application. On the cshtml page, I have a data table that I am trying to format a date like M/dd/yyyy. My issue is that when the date is null, it displays "1/01/0001". I would like for it to just display blank if it is null. My code is below.

                            <td>@jobinfo.MLR_Submission_Date.ToLocalTime().ToString("M/dd/yyyy")</td>

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Jose Gabriel Ortega CastroTop Rated Freelancer on MS Technologies
Awarded 2018
Distinguished Expert 2018

Commented:
I've added a validator on the model like this:

        public bool isItEmpty(DateTime dt)
        {
            DateTime tester = new DateTime(1970, 01, 01, 0, 0, 0, 0);

            if (dt > tester)
            {
                return true;
            }

            return false;
        }

Open in new window


And then use it on the View like this:
<table>
    <thead>Mix</thead>
    <tbody>
    <tr>
        @if (!(Model.isItEmpty(Model.EmptyDate)))
        {
            <td>Null</td>
        }
        else
        {
            <td>@Model.TodayDate</td>
        }

    </tr>
    
    
    
    <tr>
        @*Change value*@

        @{
            Model.EmptyDate = @Model.TodayDate;
        }
        @if (!(Model.isItEmpty(Model.EmptyDate)))
        {
            <td>Null</td>
        }
        else
        {
            <td>@Model.TodayDate</td>
        }

    </tr>
    </tbody>
</table>

Open in new window


Full code is on GitHub, right here https://github.com/j0rt3g4/ExpertsExchange

Screenshot_1.png
Miguel OzSenior Software Engineer
Top Expert 2009

Commented:
Create a new property (expression-bodied member) on your model: (jobinfo class)

property Submission_DateAsString  => MLR_Submission_Date > DateTime.MinValue ? Dt.ToString("M/dd/yyyy"): "";

Open in new window


then on your view:

<td>@jobinfo.Submission_DateAsString</td>

Open in new window


This is a clean solution that hides away the formatting aspects of your date time and keep it in the model.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial