Parse String (yyyymmm) Format to DateTime?

岁酱吖の 提交于 2021-02-11 16:01:49

问题


I have a field called Accounting Period as char, [AccountingPeriod] [char](6), how can I parse it to DateTime Format using DatePicker?

I used this KendoGrid for DatePicker

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

I have the date: 199805


回答1:


Okay, as from the comments I have understood that you have a date in "yyyyMM" format and from that you want the magical line of code to produce you an Object of type DateTime. You can do it using this line of code:

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

Feel free to modify it according to your needs.

UPDATE:

Regarding your assignment of the date to the Kendo datepicker, I would suggest you to create a method and call it inside of the Value() method. Something similar to this:

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

And then you can just call it inside the Value() method something like below:

@(
    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: I have not tested the code, just fire in the air after going through this article. So, It might need some Love.



来源:https://stackoverflow.com/questions/61298033/parse-string-yyyymmm-format-to-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!