2013-06-27 30 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