Home > Back-end >  Change date format in Razor
Change date format in Razor

Time:12-30

I am writing a C# application and I'm using Entity and MVC. I have a form in my index view, where the user can set a mininum date and a maximum date to be searched. However the format is MM/dd/YYYY. I want to set it to dd/MM/yyyy.

        <div >
            <form  asp-action="SimpleSearch">
                <fieldset>
                    <legend>Simple Search</legend>
                    <div >
                        <label for="minDate" >Mini Date</label>
                        <div >
                            <input type="date" name="minDate" asp-format="{0:dd/MM/yyyy}"   />
                        </div>
                    </div>
                    <div >
                        <label for="maxDate" >Max Date</label>
                        <div >
                            <input type="date" name="maxDate" asp-format="{0:dd/MM/yyyy}"   />
                        </div>
                    </div>
                    <div >
                        <div >
                            <button type="submit" >Submit</button>
                        </div>
                    </div>
                </fieldset>
            </form>
        </div>
    </div>

I've tried this comand, but it's not working. The date's format does not change.

   <input type="date" name="minDate" asp-format="{0:dd/MM/yyyy}"   />

CodePudding user response:

Did you try to add the following attributes on your Date property?

[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]

Is a Date type right? And not a DateTime?

CodePudding user response:

Edit the model which is including the min and max date and set the following attributes :

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime MinDate {Get; Set;}

And don't forget to add :

using System.ComponentModel.DataAnnotations;
  • Related