【问题标题】:Parse String (yyyymmm) Format to DateTime?将字符串(yyyymmm)格式解析为日期时间?
【发布时间】:2020-04-19 00:24:27
【问题描述】:

我有一个名为Accounting 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

【问题讨论】:

  • 请举例说明你得到了什么以及你期望的结果
  • @Barns 我添加了示例:我有日期:199805
  • 请尽量保持一致。标题显示格式“yyyymmm”,您的代码显示“MMyyyy”,但您的日期示例是 199805,根据代码,年份 = 9805 和月份 = 19。
  • @Barns 对不起,我修好了
  • 所以“199805”是输入。预期的输出是什么?

标签: c# asp.net kendo-ui datepicker


【解决方案1】:

好的,从 cmets 中我了解到,您有一个“yyyyMM”格式的日期,并且您希望神奇的代码行为您生成一个 DateTime 类型的对象。您可以使用这行代码来完成:

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:我没有测试过代码,只是在经历了article之后在空中开火。所以,它可能需要一些爱。

【讨论】:

  • 谢谢,我如何加载到日期选择器? ` @( Html.Kendo().DatePicker() .Name(nameof(InvoiceDTO.AccountingPeriod)) .Format("{0:yyyyMM}") .HtmlAttributes(new { @class= "form-control", style = "宽度:50%" }) )`
  • 好吧,你有DateTime对象类型的日期,你为什么不把它提供给Value方法呢?见:demos.telerik.com/aspnet-mvc/datepicker
猜你喜欢
  • 2019-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多