1

I have below entity in a mvc model:

[Display(Name = "Date Of Birth")]
public DateTime? DateOfBirth { get; set; }

and I am using it in a view as:

<td title="@u.CreatedDate">
    @if (@u.DateOfBirth != null)
    {
        @u.DateOfBirth
    }
</td>

This is working piece of code but I want to show this date in dd/mm/yyyy format.

I have tried something like this:

1. string.Format("dd/MM/yyyy", u.DateOfBirth);

2.  [Display(Name = "Date Of Birth")]
    [DisplayFormat (DataFormatString="dd/MM/yyyy")]
    public DateTime? DateOfBirth { get; set; }

But nothing works fine for me. Please help

5
  • [DisplayFormat (DataFormatString="dd/MM/yyyy")] works fine if you use @Html.DisplayFor(m => m.DateOfBirth). Alternatively use @u.DateOfBirth.ToString("dd/MM/yyyy") Commented Jun 30, 2016 at 12:02
  • Thanks @StephenMuecke. I have already tried this but it is also not working. It is showing an error that "No overload method for ToString() takes 1 argument" Commented Jun 30, 2016 at 12:06
  • If its nullable, then you need to use @u.DateOfBirth.Value.ToString("dd/MM/yyyy") Commented Jun 30, 2016 at 12:09
  • Thanks @StephenMuecke, @u.DateOfBirth.Value.ToString("dd/MM/yyyy") - worked for me. Commented Jun 30, 2016 at 12:13
  • If you put this as answer, I can up vote and select it as correct answer Commented Jun 30, 2016 at 12:15

1 Answer 1

6

3 options you can use

@Html.DisplayFor(m => u.DateOfBirth) // assumes you have [DisplayFormat(DataFormatString="{0:dd/MM/yyyy}")]

@String.Format("{0:dd/MM/yyyy}", u.DateOfBirth)

@u.DateOfBirth.Value.ToString("dd/MM/yyyy")

In the first 2 cases, you do not need the @if (@u.DateOfBirth != null) check

Sign up to request clarification or add additional context in comments.

1 Comment

this answer is the best where i find DataFormatString , becase this can avoid null problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.