【问题标题】:Convert to DateTime from a string '10-April-2020'从字符串 '10-April-2020' 转换为 DateTime
【发布时间】:2023-03-06 03:10:01
【问题描述】:

在转换我从网络表单收到的日期字符串时寻求帮助,其中格式类似于“2020 年 4 月 10 日”。我需要以美国日期格式“yyyy-mm-dd”将其保存到数据库中,以便提供的示例日期为“2020-04-10”。

这是我到目前为止所拥有的,它抱怨它不是有效的日期时间。

    string LicenseExpiry = LicenseExpiry.Text;
    IFormatProvider culture = new CultureInfo("en-US", true);
    DateTime dateExpires = DateTime.ParseExact(LicenseExpiry, "yyyy-MM-dd", culture);

我也尝试了以下方法,但也失败了。

DateTime dateExpires;
string LicenseExpiry = LicenseExpiry.Text;
IFormatProvider culture = new CultureInfo("en-US", true);
if (DateTime.TryParseExact(LicenseExpiry, "yyyy-MM-dd", culture, DateTimeStyles.None, out dateExpires))
{ 
    // Do something
}

任何人都可以帮助尝试查看问题所在吗?我也不允许更改 Ui/Form 来进行任何客户端日期操作,因此我的解决方案需要在 C# 代码隐藏文件中完成。

【问题讨论】:

  • 您的数据是10-April-2020 形式的字符串,与您指定的"yyyy-MM-dd" 格式完全不同。 ParseExact 表示您将指定数据的确切格式。Standard date and time format strings

标签: c# datetime date-parsing


【解决方案1】:

MM 表示月份编号(从 01 到 12)

要解析 2020 年 4 月 10 日,您 需要MMMM,见 Custom date and time format strings

“MMMM”自定义格式说明符代表月份的全名

【讨论】:

    猜你喜欢
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    • 2014-01-15
    • 2011-10-16
    • 2016-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多