簡體   English   中英

將字符串(yyyymmm)格式解析為日期時間?

[英]Parse String (yyyymmm) Format to DateTime?

我有一個名為 Account Period as char 的字段[AccountingPeriod] [char](6) ,如何使用 DatePicker 將其解析為 DateTime 格式?

我將這個 KendoGrid 用於 DatePicker

@(
    Html.Kendo().DatePicker()
        .Name(nameof(InvoiceDTO.AccountingPeriod))
        .Format("{0:yyyyMM}")
        .HtmlAttributes(new { @class = "form-control", style = "width:50%" })
)

我有日期: 199805

好的,從評論中我了解到您有一個“yyyyMM”格式的日期,並且您希望神奇的代碼行為您生成一個DateTime類型的 Object 。 您可以使用這行代碼來做到這一點:

DateTime.TryParseExact("199805", "yyyyMM", CultureInfo.InvariantCulture, DateTimeStyles.None, out var theDate);

隨意根據您的需要進行修改。

更新:

關於您將日期分配給Kendo日期選擇器,我建議您創建一個方法並在Value()方法中調用它。 與此類似的東西:

@functions{ 
    public DateTime GetDate(string strDate)
    {
        if (DateTime.TryParseExact(strDate, "yyyyMM", CultureInfo.InvariantCulture, DateTimeStyles.None, out var theDate))
        {
            return theDate;
        }
        return DateTime.Now;
    }
}

然后你可以在Value()方法中調用它,如下所示:

@(
    Html.Kendo().DatePicker()
    .Name(nameof(InvoiceDTO.AccountingPeriod))
    .Value(GetDate(InvoiceDTO.AccountingPeriod)) // I assume AccountPeriod is of type string.
    // .Format("{0:yyyyMM}") I do not think we are going to need this after the date is parsed into the required type.
    .HtmlAttributes(new { @class = "form-control", style = "width:50%" })
)

PS:我沒有測試過代碼,看完這篇文章就開槍了。 所以,它可能需要一些愛。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM