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

Vipul
  • 356
  • 6
  • 18
  • `[DisplayFormat (DataFormatString="dd/MM/yyyy")]` works fine if you use `@Html.DisplayFor(m => m.DateOfBirth)`. Alternatively use `@u.DateOfBirth.ToString("dd/MM/yyyy")` –  Jun 30 '16 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" – Vipul Jun 30 '16 at 12:06
  • If its nullable, then you need to use `@u.DateOfBirth.Value.ToString("dd/MM/yyyy")` –  Jun 30 '16 at 12:09
  • Thanks @StephenMuecke, @u.DateOfBirth.Value.ToString("dd/MM/yyyy") - worked for me. – Vipul Jun 30 '16 at 12:13
  • If you put this as answer, I can up vote and select it as correct answer – Vipul Jun 30 '16 at 12:15

1 Answers1

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