D-W
D-W

Reputation: 5341

ASP.NET MVC Nullable Datetime

Ok, I have a Client object which has a nullable datetime property for "DateOfBirth" So from the UI, we dont mind if the dateofbirth is not entered, however the issue im having is when displaying that future client, I want to format the datetime like so

@client.DateOfBirth.ToString("dd-MMM-yyyy")

but the issue is that it may return null (from which I dont want to display anything), how do I handle this issue from the UI?

Upvotes: 1

Views: 621

Answers (3)

Marc
Marc

Reputation: 992

My solution to this was to expose the date (in my case, date of birth) as a string via the view model and use .AsDateTime() to cast it back to a DateTime.

private DateTime _dateOfBirth;
[Required(ErrorMessage = "Please enter a date of birth. ")]
public String DateOfBirth {
    get { return (_dateOfBirth.ToShortDateString() == DateTime.MinValue.ToShortDateString()) ? null : _dateOfBirth.ToShortDateString(); }
    set { _dateOfBirth = value.AsDateTime(); }
}

Upvotes: 0

CodingIntrigue
CodingIntrigue

Reputation: 78525

Check for null before calling ToString:

@(client.DateOfBirth != null ? client.DateOfBirth.ToString("dd-MMM-yyyy") : "Not Selected")

You can also wrap this in a static class for code re-use:

public static class Utils {
    public static string FriendlyDate(DateTime? value) {
        if(value == null) return "Not Selected";
        return value.ToString("dd-MMM-yyyy")
    }
}

And in your View:

@Utils.FriendlyDate(client.DateOfBirth)

Upvotes: 1

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38468

You can check if it's null before displaying it:

@if(client.DateOfBirth.HasValue)
{
    @client.DateOfBirth.ToString("dd-MMM-yyyy")
}

Upvotes: 3

Related Questions