简体   繁体   中英

SQL Server 2012 Date datatype contains 12:00:00AM

I have a MVC CRUD site that has a Date Approved Textbox. When the new entry is created it is stored properly as "dd-MM-yyyy" in the SQL Sever. When I want to update an entry the Date Required textbox contains the date AND 12:00:00AM . I'm guessing this is because SQL Server is a date datatype and .Net is a DateTime. Any idea how to get rid of the 12:00:00AM ?

Failed attempts...

I've tried adding it to my viewmodel

[DisplayFormat(DataFormatString = "{0:MM-dd-yyyy}", ApplyFormatInEditMode = true)]
[Required(ErrorMessage="Required")]
[DataType(DataType.Date)]
[Display(Name="Date Requested")]
public DateTime?  Date_Requested { get; set; }

and also...

string test = Convert.ToDateTime(model.Date_Requested).ToString;

EDIT the html textbox

@Html.TextBoxFor(model => model.Date_Requested,new {@class="datepicker" })

EDIT JQuery DatePicker

$(".datepicker").datepicker({
    onSelect: function () {
        $(this).valid();
    }
});

you could add another property, using ToShortDateString :

public string DateRequestedShortDate 
{ 
    get 
    {
        return Date_Requested == null ? "" : Date_Requested.ToShortDateString();
    }
}

or simply set the textbox value to the ShortDateString to keep your binding

TextBoxFor does not honor format attributes (not sure if this is intended or a bug). You can either use EditorFor :

@Html.EditorFor(model => model.Date_Requested,new {@class="datepicker" })

or set the format in TextBoxFor :

@Html.TextBoxFor(model => model.Date_Requested,
                          new {
                               @class="datepicker", 
                               @Value = Model.Date_Requested.ToString("MM-dd-yyyy") 
                              });

Expanding on Jonesy answer from above.

public string DateRequestedShortDate 
{ 
get 
{
    return Date_Requested == null ? "" : Date.Parse(Date_Requested).ToShortDateString();
}
}

Parse won't mess up the data being inserted into SQL , hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM