简体   繁体   中英

Parse String (yyyymmm) Format to DateTime?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM