只显示日期不显示时间 [英] Display only date and no time

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

问题描述

在 MVC razor 中,我像这样将当前日期放入数据库中..

In MVC razor, I am putting current date in the database like this..

model.Returndate = DateTime.Now.Date.ToShortDateString();

由于数据库字段是日期时间数据类型并且我正在将当前日期转换为字符串格式,所以这不起作用..我该怎么做?我正在使用字符串格式,因为我想要 mm/dd/yyyy 格式的日期而不是 mm/dd/yyyy hh:mm:ss 时间格式..

Since the database field is a datetime datatype and I am converting the current date to string format, this is not working.. how can I do this? I am doing the string format because I want the date in mm/dd/yyyy format and not in mm/dd/yyyy hh:mm:ss time format..

在控制器中我有

var model = new ViewModel();
model.ReturnDate = DateTime.Now;            
return PartialView("PartialView", model);  

在局部视图中,我有

@Html.EditorFor(model => model.Returndate)

这是将日期显示为日期和时间的地方...我只想显示日期.不是时候.我希望这个编辑解释得更好.

This is where its displaying the date as Date and Time together... I want just the date to be displayed. Not the time. I hope this edit explains better.

推荐答案

如果 SQL 中的列类型是 DateTime,那么它会存储一个时间,你通过或不通过.

If the column type is DateTime in SQL then it will store a time where you pass one or not.

最好正确保存日期:

model.ReturnDate = DateTime.Now;

然后在需要显示时格式化:

and then format it when you need to display it:

@Html.Label(Model.ReturnDate.ToShortDateString())

或者,如果您使用的是 EditorFor:

Or if you're using EditorFor:

@Html.EditorFor(model => model.ReturnDate.ToShortDateString())

@Html.EditorFor(model => model.ReturnDate.ToString("MM/dd/yyyy"))

要向模型添加属性,请添加以下代码:

To add a property to your model add this code:

public string ReturnDateForDisplay
{
    get
    {
       return this.ReturnDate.ToString("d");
    }
}

然后在你的 PartialView 中:

Then in your PartialView:

@Html.EditorFor(model => model.ReturnDateForDisplay)

我只想澄清这个答案,我说如果您使用的是 EditorFor",这意味着您需要有一个 EditorFor 模板来表示您要表示的值类型.

I just want to clarify for this answer that by my saying 'If you're using EditorFor', that means you need to have an EditorFor template for the type of value you're trying to represent.

编辑器模板是在 MVC 中管理重复控件的一种很酷的方式:

Editor templates are a cool way of managing repetitive controls in MVC:

http://coding-in.net/asp-net-mvc-3-how-to-use-editortemplates/

您可以像我上面所做的那样将它们用于诸如 String 之类的幼稚类型;但它们特别适合让您为更复杂的数据类型设置一组输入字段的模板.

You can use them for naive types like String as I've done above; but they're especially great for letting you template a set of input fields for a more complicated data type.

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

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