问题
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