stefan.stt
stefan.stt

Reputation: 2627

Format date in a View in ASP.NET Core MVC

How can I make the date format to be "dd.MM.yyyy" because whatever I do it is always "MM/dd/yyyy"

View part:

<div class="col-md-6 col-xs-6 pull-left">
    <label asp-for="@Model.RequestRegistrationDateFrom"></label>
    <div class="input-group date">
        <input type="text" asp-for="@Model.RequestRegistrationDateFrom" class="form-control js-datepicker pull-left" />
        <div class="input-group-append">
            <span class="input-group-text calendar-fa"></span>
        </div>
    </div>
</div>

Model property:

[BindProperty(SupportsGet = true)]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "dd.MM.yyyy")]
[Display(Name = "Date from", ResourceType = typeof(string))]
public DateTime? RequestRegistrationDateFrom { get; set; }

Upvotes: 1

Views: 5352

Answers (5)

samer shalha
samer shalha

Reputation: 31

It's very simple, do the following:

public class YourClassName
{
    [DataType(DataType.Date)]
    public DateTime Date { get; set; } = DateTime.Today;
}

Upvotes: 1

Muhammad Ahsan Saifi
Muhammad Ahsan Saifi

Reputation: 33

For .Net Core MVC Views

For Nullable

public DateTimeOffset? CreatedAt { get; set; }

@obj.CreatedAt.Value.ToString("dd-MM-yy hh:mm:ss")

For Non Nullable

public DateTimeOffset DeliveryDate { get; set; }

@obj.DeliveryDate.Date.ToString("dd-MM-yy")

Upvotes: 0

Wasiim
Wasiim

Reputation: 27

In your model:

[Column(TypeName = "Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime start_date { get; set; }

In your view:

<td>@item.start_date.ToString("dd/MM/yyyy")</td>

Upvotes: 0

Yas Ikeda
Yas Ikeda

Reputation: 1096

I have heard such case as you are experiencing. Unfortunately, I haven't got it myself, and haven't got a chance to dig into what's actually wrong behind DisplayFormat attribute.

In that case, passing formatted string to value attribute worked.

<input type="text" asp-for="RequestRegistrationDateFrom" value="@Model.RequestRegistrationDateFrom.ToString("dd.MM.yyyy")" class="form-control js-datepicker pull-left" />

Try it for now. Hopefully, it would work in your case too.

If you could post a solution here when you figure out the problem behind, that'll be awesome. I'm interested in it.

Upvotes: 1

Floor
Floor

Reputation: 216

This should work:

[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]

Upvotes: 1

Related Questions