2013-06-27 32 views
1

在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; 
       } 
      } 
     } 

    } 

这里是异常消息:

enter image description here

它说: “System.FormatException:该字符串未被识别为一个DateTime的Valide”

+0

@Sander Stackoverflow之前,我找不到任何快速搜索。而[链接的问题](http://stackoverflow.com/questions/5793163/c-sharp-winforms-datetimepicker-custom-format)绝对不会帮助沃尔特。 –

+0

为什么你的问题标记为json,json如何被invloved?如果你想解析出一个json响应,有很多简单的方法可以做到,然后手动解析我们的每个部分。 –

回答

11

尝试用这样的事情...

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

...,并与date变量,你只需要...

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

对OP的建议:使用'TryParseExact'方法避免'FormatException' – NominSim

+0

好!更新你的建议! – HuorSwords

+0

我试过了你的提示,形式确定!但是,我不知道为什么,我在我的DataGrid上有一个FormatException。实际上,我使用此代码来检查输入的数据是否是日期。我编辑了我的代码。你有什么想法吗?谢谢 –

3

HuorSwords不(比使用string作为输入值等),但得到的答复并不严格回答这个问题:为了显示的要求之日起,您需要格式化的事实后的字符串:虽然我敢肯定,这个问题已经回答了上

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

这是真的......使用受保护的关键字作为变量...不可饶恕!更新!谢谢。 – HuorSwords