c# - 为什么日期时间选择器会这样?

标签 c# date datetime datepicker asp.net-mvc-5

我有型号:

const string MyDateFormat = "yyyy-MM-dd";

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = MyDateFormat, ApplyFormatInEditMode = true)]
public DateTime Date { get; set; }

并查看:

@Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control datepicker" } })

由于某种原因,在表单加载时没有设置模型值,我想知道为什么?
我必须手动:

<script type="text/javascript">
    $(document).ready(function () {
        var elem = $("#Date").val('@Model.Date.ToString(MyDateFormat)');
    });
</script>

但是,在表单中我看到 dd.MM.yyyy (这是我的计算机区域设置)格式,为什么?
enter image description here

如果尝试设置 MyDateFormat = "dd.MM.yyyy"不起作用,请参阅 dd.MM.yyyy:
enter image description here

据我所知,yyyy-MM-dd是.net运行时本地格式,dd.MM.yyyy是我的计算机本地格式。
如何做到不依赖于计算机的区域设置和 .net 运行时区域设置?

最佳答案

我相信您错过了表达式周围的大括号。

尝试将表达式 yyyy-MM-dd 括在大括号中,如下所示 {0:yyyy-MM-dd}

const string MyDateFormat = "{0:yyyy-MM-dd}";

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = MyDateFormat, ApplyFormatInEditMode = true)]
public DateTime Date { get; set; }

您还可以在 View 中使用以下内容,而不是使用 DisplayFormat 属性来装饰模型属性。

@Html.TextBoxFor(model => model.Date, "{0:yyyy-MM-dd}", new { @class="datePicker"});

关于c# - 为什么日期时间选择器会这样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33585031/

相关文章:

c# - 转换为字符串时删除无关紧要的小数位 (C#)

r - 在 R 中提取奇怪格式 (EURO MTH/MM/YYYY) 的日期

php - 如何在 PHP 中为 MongoDB 返回 ISO 日期格式?

mysql - 错误代码 : 1064 while trying to retrieve values between timestamps

c++ - 使用服务器时间的 QSqlQuery UPDATE/INSERT DateTime(例如 CURRENT_TIMESTAMP)

c# - 项目符号点不替换 - csv 到 xml

c# - 尽管未更新,但 Winforms 控件闪烁

c# - 此 linq 代码中的多个 orderby

java - 将日期时间插入数据库

delphi - 在 TDateTimePicker On 下拉菜单中设置日期