0

这是我的 VB.Net 项目。在这个阶段,我将数据从 excel 拉到 VS2010。

在这个我有字符串格式的日期 25.10.2013,我想在数据网格中添加这个日期,但它显示“从字符串转换”“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

获取今日功能:

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
4

1 回答 1

2

我假设该方法getToday应该返回今天的日期字符串,您可以通过Date.Today.ToShortDateStringor获得它Date.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
于 2013-10-30T08:40:32.023 回答