Formatting DateTime in model to Date only in View

16,386
public class AsOfdates
{
    public string DisplayDate { get; set; }
    private DateTime TheDate;
    public DateTime DateValue { get { return TheDate.Date; } set { TheDate = value; } }

}
Share:
16,386
Prakhar Mishra
Author by

Prakhar Mishra

I am IoT Senior Software Engineer at Koch Industries. Currently working on Java, Golang, MySQL, and AWS services.

Updated on November 25, 2022

Comments

  • Prakhar Mishra
    Prakhar Mishra over 1 year

    I am using ASP.NET MVC 5. I have a date only picker in my create and edit form. In create form, its working just fine. But in edit form, it loads previously saved DateTime as dd-MM-yyyy hh:mm:ss. On clicking on textbox, my date picker appears with a calendar of Dec, 1899. Only if I can format my DateTime, it will work fine.

    Though, I know how to solve this problems in Struts 2, I am new to ASP.NET MVC. Can anybody please tell me how to format my DateTime model property to Date only in my View?

    Here is my model:-

    public class Vehicle
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int VehicleId
        { get; set; }
    
        [Display(Name = "Vehicle name")]
        [StringLength(100)]
        public String Name
        { get; set; }
    
        [Required]
        public String VehicleType
        { get; set; }
    
        [Required]
        [StringLength(20)]
        [Display(Name = "Registration no.")]
        public String RegNo
        { get; set; }
    
        [DataType(DataType.Date)]
        [Display(Name = "Insurance date")]
        public DateTime InsuranceDate
        { get; set; }
    }
    

    Here is a part of my view:-

    <div class="form-group">
                        @Html.LabelFor(model => model.InsuranceDate, new { @class = "control-label col-md-2" })
                        <div class="col-md-6 input-group date" id="datePick">
                            @Html.EditorFor(model => model.InsuranceDate, new { @class = "form-control", id = "datePickText", placeholder = "Enter Insurrance Date" })<span class="input-group-addon"><i class="glyphicon glyphicon-th"></i></span>
                            @Html.ValidationMessageFor(model => model.InsuranceDate)
                        </div>
                    </div>
    
  • Prakhar Mishra
    Prakhar Mishra about 10 years
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] not working on InsuranceDate