2013-10-30 150 views
0

這是我的VB.Net項目。在這個階段,我將數據從excel提取到VS2010。將字符串轉換爲日期

在這裏我有日期字符串格式25.10.2013,我想添加這個日期在datagrid,但它顯示「從字符串轉換」「25.10.2013」​​鍵入'日期'是無效的「錯誤。

請同時檢查以下值編碼(功能&雖然),並提供我的解決方案來解決這個

If DialogResult = Windows.Forms.DialogResult.OK Then 
    Try 
    Dim objreader As New System.IO.StreamReader(OpenDLG.FileName) 
    linecount = 0 
    dupord = 0 
    nooford = 0 

    While Not objreader.EndOfStream 
     fallout = objreader.ReadLine 
     If linecount >= 0 Then 
      If fallout = "" Then 
       Exit While 
      End If 
     ' Dim tmpArray() As String = Regex.Split(Trim(velocityfallout), " ") 
      Dim tmpArray() As String = Regex.Split(Trim(fallout), ",") 
      If tmpArray(0) = "" Then 
      Exit While 
      End If 
      pono = tmpArray(0) 
      issue = tmpArray(1) 
      falldate = getToday(tmpArray(3)) 
      ftype = "Velocity" 
      checkfallout("Velocity", "", "", falldate, "", pono, "", issue, "") 
      nooford = nooford + 1 

     End If 
     linecount += 1 
    End While 

GetToday功能:

Function getToday(ByVal dateStr As Date) As String 

    Dim dateStrRet As String 

    dateStrRet = CStr(DatePart("yyyy", dateStr)) & "-" 

    If DatePart("m", dateStr) < 10 Then 
     dateStrRet = dateStrRet & "0" & CStr(DatePart("m", dateStr)) & "-" 
    Else 
     dateStrRet = dateStrRet & CStr(DatePart("m", dateStr)) & "-" 
    End If 

    If DatePart("d", dateStr) < 10 Then 
     dateStrRet = dateStrRet & "0" & CStr(DatePart("d", dateStr)) 
    Else 
     dateStrRet = dateStrRet & CStr(DatePart("d", dateStr)) 
    End If 

    Return dateStrRet 
End Function 

回答

2

我認爲方法getToday應該返回今天的日期字符串,你可以通過Date.Today.ToShortDateStringDate.Today.ToString("d")得到它。但是,如果您希望它採用特定格式,例如使用英文或德文日期分隔符,則必須提供適當的IFormatProvider。德國文化"de-DE"是例如使用.作爲日期分隔符:

'fallback culture 
Private Shared ReadOnly deCulture As CultureInfo = CultureInfo.CreateSpecificCulture("de-DE") 

Function getToday(ByVal dt As Date, Optional provider As IFormatProvider = Nothing) As String 
    ' force culture "de-DE" (germany) if no one was provided: 
    If provider Is Nothing Then provider = deCulture 
    Return dt.ToString("d", provider) 
End Function 

因爲它不是那麼清楚,也許你也有問題,解析字符串中的日期。那麼你必須使用Date.ParseDate.ParseExact(或TryParse方法)與適當的文化:

Dim dateStr As String = tmpArray(3) 
Dim deCulture As CultureInfo = CultureInfo.CreateSpecificCulture("de-DE") 
Dim dt As Date 
If Date.TryParse(dateStr, deCulture, DateTimeStyles.None, dt) Then 
    dateStr = getToday(dt, deCulture) ' you can omit deCulture since that is default here 
End If