使用razor转换日期时间格式

发布于 2024-10-11 12:05:40 字数 176 浏览 7 评论 0原文

以下有什么问题吗?

@Convert.ToDateTime((@item.Date.ToShortDateString())," dd - M - yy")

@item.Date 显示 20/11/2005 12:00 am,我想显示 2011 年 11 月 20 日

What is wrong with the following?

@Convert.ToDateTime((@item.Date.ToShortDateString())," dd - M - yy")

@item.Date is showing 20/11/2005 12:00 a.m and I want to display 20 Nov 2011

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

清泪尽 2024-10-18 12:05:40

尝试:

@item.Date.ToString("dd MMM yyyy")

或者您可以使用 [DisplayFormat]视图模型上的 属性:

[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
public DateTime Date { get; set }

在您的视图中:

@Html.DisplayFor(x => x.Date)

Try:

@item.Date.ToString("dd MMM yyyy")

or you could use the [DisplayFormat] attribute on your view model:

[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
public DateTime Date { get; set }

and in your view simply:

@Html.DisplayFor(x => x.Date)
神爱温柔 2024-10-18 12:05:40

这是解决方案:

@item.Published.Value.ToString("dd. MM. yyyy")

ToString() 之前使用 Value

This is solution:

@item.Published.Value.ToString("dd. MM. yyyy")

Before ToString() use Value.

比忠 2024-10-18 12:05:40

在 MVC 4.0 中尝试一下

@Html.TextBoxFor(m => m.YourDate, "{0:dd/MM/yyyy}", new { @class = "datefield form-control", @placeholder = "Enter start date..." })

Try this in MVC 4.0

@Html.TextBoxFor(m => m.YourDate, "{0:dd/MM/yyyy}", new { @class = "datefield form-control", @placeholder = "Enter start date..." })
梦断已成空 2024-10-18 12:05:40

[DisplayFormat] 属性仅在 EditorFor/DisplayFor 中使用,而不是由 TextBoxFor 等原始 HTML API 使用。我通过执行以下操作使其工作:

模型:

[Display(Name = "When was that document issued ?")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
public DateTime? LiquorLicenceDocumentIssueDate { get; set; }

视图:

        <div id="IsLiquorLicenceDocumentOnPremisesYes" class="groupLongLabel">
            @Html.LabelFor(m => m.LiquorLicenceDocumentIssueDate)
            <span class="indicator"></span>
            @Html.EditorFor(m => m.LiquorLicenceDocumentIssueDate)
            <span id="validEmail"></span>
            <br />
            @Html.ValidationMessageFor(m => m.LiquorLicenceDocumentIssueDate)
        </div>

输出:
2011 年 12 月 30 日

相关链接:

http:// /msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayformatattribute.applyformatineditmode.aspx

The [DisplayFormat] attribute is only used in EditorFor/DisplayFor, and not by the raw HTML APIs like TextBoxFor. I got it working by doing the following,

Model:

[Display(Name = "When was that document issued ?")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
public DateTime? LiquorLicenceDocumentIssueDate { get; set; }

View:

        <div id="IsLiquorLicenceDocumentOnPremisesYes" class="groupLongLabel">
            @Html.LabelFor(m => m.LiquorLicenceDocumentIssueDate)
            <span class="indicator"></span>
            @Html.EditorFor(m => m.LiquorLicenceDocumentIssueDate)
            <span id="validEmail"></span>
            <br />
            @Html.ValidationMessageFor(m => m.LiquorLicenceDocumentIssueDate)
        </div>

Output:
30/12/2011

Related link:

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayformatattribute.applyformatineditmode.aspx

情丝乱 2024-10-18 12:05:40

下面的代码会对您有所帮助

@Html.Label(@item.Date.Value.ToString("dd - M - yy"))

Below code will help you

@Html.Label(@item.Date.Value.ToString("dd - M - yy"))
鸢与 2024-10-18 12:05:40

对于 Razor,将文件 DateTime.cshtml 放在 Views/Shared/EditorTemplates 文件夹中。 DateTime.cshtml 包含两行,并生成一个日期格式为 9/11/2001 的 TextBox。

@model DateTime?
@Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = "datePicker" })

For Razor put the file DateTime.cshtml in the Views/Shared/EditorTemplates folder. DateTime.cshtml contains two lines and produces a TextBox with a date formatted 9/11/2001.

@model DateTime?
@Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = "datePicker" })
陈甜 2024-10-18 12:05:40

一般来说,书面月份转义为 MMM,4 位年份转义为 yyyy,因此您的格式字符串应类似于“dd MMM yyyy”

DateTime.ToString("dd MMM yyyy")

In general, the written month is escaped as MMM, the 4-digit year as yyyy, so your format string should look like "dd MMM yyyy"

DateTime.ToString("dd MMM yyyy")
迷雾森÷林ヴ 2024-10-18 12:05:40

我无法完全根据上述建议来完成这项工作。包括 DataTypeAttribute [DataType(DataType.Date)] 似乎解决了我的问题,请参阅:

模型

[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime RptDate { get; set; }

视图

@Html.EditorFor(m => m.CLPosts.RptDate)

HTH

I was not able to get this working entirely based on the suggestions above. Including the DataTypeAttribute [DataType(DataType.Date)] seemed to solve my issue, see:

Model

[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime RptDate { get; set; }

View

@Html.EditorFor(m => m.CLPosts.RptDate)

HTH

走过海棠暮 2024-10-18 12:05:40

对于所有给定的解决方案,当您在现代浏览器(如 FF)中尝试此操作时,并且您已设置

// Model
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime Start { get; set; }

// View
<div class="form-group">
    @Html.LabelFor(model => model.Start, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Start, "{0:dd-MM-yyyy}", new { htmlAttributes = new { @class = "form-control"} })
    </div>
</div>

将渲染的正确模型 mvc(5) (输入的 type 设置为 >日期基于您模型中的日期设置!)

<div class="col-md-10">
<input class="form-control text-box single-line" data-val="true" data-val-date="The field Start must be a date." data-val-required="The Start field is required." id="Start" name="Start" value="01-05-2018" type="date">
        <span class="field-validation-valid text-danger" data-valmsg-for="Start" data-valmsg-replace="true"></span>
</div>

浏览器将显示

在此处输入图像描述

要解决此问题,您需要将类型更改为文本而不是日期(如果您想使用自定义日历)

@Html.EditorFor(model => model.Start, "{0:dd-MM-yyyy}", new { htmlAttributes = new { @class = "form-control", @type = "text" } })

For all the given solution, when you try this in a modern browser (like FF), and you have set the correct model

// Model
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime Start { get; set; }

// View
<div class="form-group">
    @Html.LabelFor(model => model.Start, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Start, "{0:dd-MM-yyyy}", new { htmlAttributes = new { @class = "form-control"} })
    </div>
</div>

mvc(5) wil render (the type of the input is set to date based on your date settings in your model!)

<div class="col-md-10">
<input class="form-control text-box single-line" data-val="true" data-val-date="The field Start must be a date." data-val-required="The Start field is required." id="Start" name="Start" value="01-05-2018" type="date">
        <span class="field-validation-valid text-danger" data-valmsg-for="Start" data-valmsg-replace="true"></span>
</div>

And the browser will show

enter image description here

To fix this you need to change the type to text instead of date (also if you want to use your custom calender)

@Html.EditorFor(model => model.Start, "{0:dd-MM-yyyy}", new { htmlAttributes = new { @class = "form-control", @type = "text" } })
§普罗旺斯的薰衣草 2024-10-18 12:05:40

根据安扬·康德(Anjan Kant)上面所说的,这就是我想出的(本来会给你一个赞成票,但我太新了)

@if (Model.Quotes != null)
        {
            foreach (var item in Model.Quotes)
            {
                <tr class="code-black">
                    <td class="td">
                        @Html.Label(@item.CreateDate.ToShortDateString())
                    </td>
                    <td class="td">
                        @Html.DisplayFor(modelItem => item.Status)
                    </td>
                    <td class="td">
                        @Html.DisplayFor(modelItem => item.ProjectName)
                    </td>
                    <td class="td usd">
                        @Html.DisplayFor(modelItem => item.Total)
                    </td>
                    <td class="td">
                        <a asp-page="../Quote/Details" asp-route- 
                                        id="@item.Id">View</a> 
                    </td>
                </tr>
            }
        }

Based on what Anjan Kant said above, this is what I came up with (would have given you an upvote but I'm too new)

@if (Model.Quotes != null)
        {
            foreach (var item in Model.Quotes)
            {
                <tr class="code-black">
                    <td class="td">
                        @Html.Label(@item.CreateDate.ToShortDateString())
                    </td>
                    <td class="td">
                        @Html.DisplayFor(modelItem => item.Status)
                    </td>
                    <td class="td">
                        @Html.DisplayFor(modelItem => item.ProjectName)
                    </td>
                    <td class="td usd">
                        @Html.DisplayFor(modelItem => item.Total)
                    </td>
                    <td class="td">
                        <a asp-page="../Quote/Details" asp-route- 
                                        id="@item.Id">View</a> 
                    </td>
                </tr>
            }
        }
萝莉病 2024-10-18 12:05:40

我在另一个问题中使用了这个答案,效果非常好:
@(item.Startdate.HasValue ? item.Startdate.Value.ToString("dd/MM/yyyy") : "Date is Empty")

如果日期列为空,Value.ToString会抛出错误,所以我们使用条件语句

灵感来自 @miroslav-holec 和 @shaiju-t 的回答

I used this from answer in another question and it works very good:
@(item.Startdate.HasValue ? item.Startdate.Value.ToString("dd/MM/yyyy") : "Date is Empty")

if the date column is null, Value.ToString will throw error, so we use condition statement

inspired from answers by @miroslav-holec and @shaiju-t

瞳孔里扚悲伤 2024-10-18 12:05:40

更改日期类型的简单方法即:

   [DataType(DataType.Date)]
   public DateTime? DataEurGbp { get; set; }

Easy way to change date type i.e:

   [DataType(DataType.Date)]
   public DateTime? DataEurGbp { get; set; }
预谋 2024-10-18 12:05:40

您可以使用 jQuery 日历来获得更好的结果,我们使用以下代码完成了此任务

<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<script>
    $(function () {
        $("#EnrollmentDate").datepicker({
            dateFormat: 'dd/M/yy'//,
            //minDate: new Date(),
            //value: new Date()
        });
    });
</script>


<form method="post">

    <div class="form-group col-4">
        <label asp-for="@Model.EnrollmentDate" class="control-label"></label>
        <input class="form-control" asp-for="@Model.EnrollmentDate" type="text">
        <span asp-validation-for="@Model.EnrollmentDate" class="text-danger"></span>
    </div>

    <div class="form-group col-4">
        <input type="submit" value="SUBMIT" class="btn btn-primary btn-sm" />
    </div>

</form>

,C# 代码使用如下

    [BindProperty]
    [DataType(DataType.Date)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MMM/yyyy}")]
    public DateTime EnrollmentDate { get; set; } = DateTime.Now.AddYears(-1);

You can use jQuery calendar for better result, we completed this task with following code

<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<script>
    $(function () {
        $("#EnrollmentDate").datepicker({
            dateFormat: 'dd/M/yy'//,
            //minDate: new Date(),
            //value: new Date()
        });
    });
</script>


<form method="post">

    <div class="form-group col-4">
        <label asp-for="@Model.EnrollmentDate" class="control-label"></label>
        <input class="form-control" asp-for="@Model.EnrollmentDate" type="text">
        <span asp-validation-for="@Model.EnrollmentDate" class="text-danger"></span>
    </div>

    <div class="form-group col-4">
        <input type="submit" value="SUBMIT" class="btn btn-primary btn-sm" />
    </div>

</form>

and the C# code use as follows

    [BindProperty]
    [DataType(DataType.Date)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MMM/yyyy}")]
    public DateTime EnrollmentDate { get; set; } = DateTime.Now.AddYears(-1);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文