【发布时间】: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