【问题标题】:String was not recognized as a valid DateTime, Jul 11, 2019字符串未被识别为有效的日期时间,2019 年 7 月 11 日
【发布时间】:2019-07-29 17:34:02
【问题描述】:

我有一个来自 Griview 单元的字符串。该字符串的值为Jul 11, 2019。我需要将其转换为 yyyy-MM-dd 格式,但在尝试转换时出现错误。

到目前为止,我已经尝试了以下方法:

  • DateTime.ParaExact(Startdatebefore, "yyyy-MM-dd",Null)
  • String.Convert("yyyy-MM-dd")

这是上下文的代码示例:

string Startdatebefore = item.Cells[4].Text;
string StartDate = DateTime.ParseExact(Startdatebefore, "yyyy-MM-dd", null).ToString();
---- // The second way of trying to convert is below and this also is not working. 
DateTime EndDate = Convert.ToDateTime(item.Cells[4].Text);
string EndDatedone = EndDate.ToString("yyyy-MM-dd");

但我仍然收到错误消息。

我在哪里犯错了?我在 Stack 和 google 上查看了很多问题,但其中大多数以前都是数字日期格式,与我遇到的错误不符。如果您知道为什么会出错,请告诉我。

【问题讨论】:

  • 为什么您的所有掩码尝试都以年份开头,而这显然不是您的输入字符串所具有的?
  • 解析格式需要匹配初始字符串的格式,而不是你要转换成的格式。试试MMM dd, yyyy
  • 您要转换的单元格中的实际值是多少?调试并首先找到它。可能有空格或其他东西,甚至没有你认为的内容
  • 在分配Startdatebefore时请显示一个实际的字符串值,而不是item.Cells[4].Text,这样我们都在同一个页面上。
  • DateTime.ParseExact 不会将一个字符串重新格式化为另一个字符串。它接受一个指定格式的字符串——你给它“MMM dd, yyyy”——并返回一个DateTime object,它根本没有特定的格式。 DateTime 有一个称为 Year 的整数属性、一个称为 Month 的整数属性、另一个称为 Day 等的整数属性,以此类推,精确到毫秒。获得该日期时间对象后,您可以使用resultingDateTime.ToString("yyyy-mm-dd") 将其转换为“yyyy-mm-dd”格式的字符串。

标签: c# parsing type-conversion


【解决方案1】:

字符串“2019 年 7 月 11 日”应该可以通过正常的 DateTime 解析器进行解析。然后,您可以将所需的格式提供给 DateTime 的 ToString 方法。

var formatted = DateTime.Parse("Jul 11, 2019").ToString("yyyy-MM-dd");
Console.WriteLine(formatted); // 2019-07-11

【讨论】:

    【解决方案2】:
    //get the string
    string Startdatebefore = item.Cells[4].Text;
    // Parse to DateTime using the original **source** format:
    DateTime StartDate = DateTime.ParseExact(Startdatebefore, "MMM dd, yyyy", null);
    // create the string from the DateTime using the **target** format
    Startdatebefore = StartDate.ToString("yyyy-MM-dd");
    

    或者在一行中:

    string Startdatebefore = DateTime.ParseExact(Startdatebefore, "MMM dd, yyyy", null).ToString("yyyy-MM-dd");
    

    最后一点:如果您这样做是为了包含在 SQL 语句中,那么您做的事情非常是错误的。

    【讨论】:

    • 非常感谢单行字符串格式和集合运行完美,我没有使用 SQL,我只需要将 asp.net gridview 中的这些数据放入 CSV 文件中。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-07
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多