MVC storing date without time

2019-09-07 11:54发布

问题:

I am trying to save the date the user enters into a database. The problem is that despite only the date showing in the text box the time is also being saved. This is what it looks like in my model.

{11/02/2015 00:00:00}

However this is what I have in my JQuery set up and how I would like it to look when saved to the database, without the time also attached.

$("#datepicker").datepicker({ dateFormat: 'dd/mm/yy' });

I assume the problem lies in my model somewhere so this is how I have it set up at the moment.

    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    public DateTime DateOfBooking { get; set; }

and this is my view,

    <div class="form-group">
        @Html.LabelFor(model => model.DateOfBooking, new { @class = "control-label col-md-2"})
        <div class="col-md-10">
            @Html.TextBoxFor(x => x.DateOfBooking, new { @id = "datepicker" })
            @Html.ValidationMessageFor(model => model.DateOfBooking)
        </div>
    </div>

回答1:

There's no way, using DateTimes, to only store/pass the date to the model. In SQL you can use a Date data type that will only store the Date part of the DateTime object from .Net. However, when you move data into/out of your model you'll always have a time component. The easiest way is to just ignore the time component and specify the display format like you're doing.

You could also use something like Noda Time that has structs for Date only types.