没有时间的MVC存储日期 [英] MVC storing date without time

查看:85
本文介绍了没有时间的MVC存储日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试保存用户输入数据库的日期.问题是,尽管仅在文本框中显示日期,但时间也被保存.这就是我的模型中的样子.

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}

但是,这是我在JQuery设置中拥有的内容,以及在不附加时间的情况下保存到数据库中时的外观.

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; }

这是我的观点,

    <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>

推荐答案

使用DateTimes无法将日期仅存储/传递给模型.在SQL中,您可以使用日期数据类型,该数据类型仅存储日期.Net的DateTime对象的一部分.但是,当您将数据移入模型或移出模型时,总是会有时间部分.最简单的方法是忽略时间分量,然后像执行操作一样指定显示格式.

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.

您还可以使用类似 Noda Time 之类的东西,它具有仅日期类型的结构.

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

这篇关于没有时间的MVC存储日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆