将字符串(yyyymmm)格式解析为DateTime? [英] Parse String (yyyymmm) Format to DateTime?
问题描述
我有一个称为会计期间"的字段,为char,[AccountingPeriod] [char](6)
,如何使用DatePicker将其解析为DateTime格式?
I have a field called Accounting Period as char, [AccountingPeriod] [char](6)
, how can I parse it to DateTime Format using DatePicker?
我将此KendoGrid用于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%" })
)
我有日期:199805
推荐答案
好的,从注释中我了解到,您有一个日期为"yyyyMM"格式的日期,并且您希望通过神奇的代码行生成一个类型为DateTime
的对象.您可以使用以下代码行做到这一点:
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.
更新:
关于将日期分配给Kendo
日期选择器的问题,建议您创建一个方法并将其在Value()
方法内部调用.与此类似:
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;
}
}
然后您可以在Value()
方法内部调用它,如下所示:
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:我尚未测试代码,经过此文章.因此,可能需要一些爱.
PS: I have not tested the code, just fire in the air after going through this article. So, It might need some Love.
这篇关于将字符串(yyyymmm)格式解析为DateTime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!