Format date in Table Display

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

Stacey FontenotAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jose Gabriel Ortega CastroEE Solution Guide/Topic Advisor and CEO Faru Bonon ITCommented:
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 EngineerCommented:
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.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET MVC

From novice to tech pro — start learning today.