【问题标题】:Parse a string to a date without slashes将字符串解析为不带斜线的日期
【发布时间】:2013-06-25 00:52:06
【问题描述】:

在 C#/Winform 中,如果用户输入:dd/mm/yyyy

,我可以将字符串解析为日期
DateTime.Parse(date).ToString();

我希望能够在没有斜杠的情况下进行解析(例如在 datagridview 或 DateTimePicker 中)。

01022012 应该被解析为01/02/2012

有人知道如何用DateTime.Parse 解析它吗?

这是我的代码:

    private void dataGridView_BadgeService_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
    {
        if (dataGridView_BadgeService.Columns[e.ColumnIndex].Name == "DateDebut" || dataGridView_BadgeService.Columns[e.ColumnIndex].Name == "DateFin")
        {
            string date = Convert.ToString(e.FormattedValue).Trim();

            if (date.Length > 0)
            {
                try
                {
                    DateTime _date;
                    DateTime.TryParseExact(date, "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out _date);
                    date = _date.ToShortDateString();
                    dataGridView_BadgeService.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = date;
                }
                catch
                {
                   MessageBox.Show("Merci de saisir une date, ou laissez cette zone vierge", "Action-Informatique", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                   e.Cancel = true;
                }
            }
        }

    }

这是异常消息:

它说:“System.FormatException:字符串不被识别为日期时间验证”

【问题讨论】:

  • @Sander 虽然我确信这个问题之前已经在 Stackoverflow 上得到了回答,但我无法通过快速搜索找到任何问题。而linked question 对沃尔特毫无帮助。
  • 为什么你的问题被标记为 json,json 是如何被引用的?如果您尝试解析 json 响应,则有很多更简单的方法可以做到这一点,然后手动解析我们的每个部分。

标签: c# .net winforms datetime formatting


【解决方案1】:

试试这样的...

string unslashedValue = "01022012"
DateTime date;
DateTime.TryParseExact(unslashedValue, "ddMMyyyy", 
                       CultureInfo.InvariantCulture, DateTimeStyles.None, date);

...并且,使用date 变量,您只需要...

string slashedValue = date.ToString("dd/MM/yyyy");

【讨论】:

  • 给OP的建议:使用TryParseExact方法避免FormatException
  • 不错!更新了您的建议!
  • 我试过你的提示,格式没问题!但是,我不知道为什么,我的 DataGrid 上有一个 FormatException。实际上,我使用此代码来检查输入的数据是否是日期。我编辑了我的代码。请问你有什么想法吗?谢谢
  • 这个FormatException 的确切信息是什么?它可以帮助我们弄清楚你在做什么......
  • "System.FormatException : 该字符串未被识别为 dateTime valide"(这是一个 DataGridView 异常)。我用截图编辑了我的帖子。
【解决方案2】:

HuorSwords 没有错误(除了使用string 作为输入值),但答案并没有严格回答问题:为了显示 em> 请求的日期,事后需要格式化为字符串:

DateTime date = DateTime.ParseExact(input, 
  "ddMMyyyy", CultureInfo.InvariantCulture);
string formattedDate = date.ToString("dd/MM/yyyy");

【讨论】:

  • 这是真的...使用受保护的关键字作为变量...不可原谅!更新!谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-10
  • 2013-06-05
  • 1970-01-01
  • 1970-01-01
  • 2016-11-19
  • 2012-05-05
相关资源
最近更新 更多