2016-04-12 14 views
0

検索した日付の文字列をアクセスデータベースから日付型に変換して月の計算をしようとしています。 私が抱えている問題は、取得した文字列型変数を日付型に変換できません。私はConvert.ToDateTime、DateTime.ParseExact()などのいくつかのメソッドを試してみました。まだ失敗します。視覚的な基本の文字列を日付型に変換する

私のコードは文字列としてpermitEndDateの列を取得できますが、日付型に変換できません。私の機能にそれを。

私はVBで新しく、多くのおかげで私の質問を読んだ人に助けてください。

マイコード:

For i As Integer = 0 To ds.Tables("lecturer").Rows.Count - 1 

     TextBox1.AppendText(ds.Tables("lecturer").Rows(i).Item(16) & vbCrLf) 
     'convert string to date type 
     Dim getDate As String = ds.Tables("lecturer").Rows(i).Item(16) 
     TextBox1.AppendText("Parse getDate: " & getDate & vbCrLf) 

     Dim expDate As DateTime = DateTime.ParseExact(getDate, "dd/MM/yyyy", CultureInfo.InvariantCulture) 
     TextBox1.AppendText("Parse expDate with date type: " & expDate & vbCrLf) 
     ' Dim permitEndDate As String = ds.Tables("lecturer").Rows(i).Item(16) 

     'expDate = Convert.ToDateTime(permitEndDate) 
     ' TextBox1.AppendText("Difference in month: " & CalculateMonth(expDate) & vbCrLf) 
    Next 

機能:

'calculation of months 
Function CalculateMonth(ByVal endDate As Date) As Integer 
    Dim result As Integer 
    '1.get today date 
    Dim currentDate As Date = Date.Now.ToString("dd/MM/yyyy") 

    'calculation formula 
    result = DateDiff(DateInterval.Month, currentDate, endDate) 

    Return result 
End Function 

だから、私のエラー "文字列は有効な日時として認識されませんでした"行は次のとおりです。日付= Date.ParseExact(のgetDate、 "DD/MM/YYYY"、CultureInfo.InvariantCulture)

+0

まず、データベース内のデータが日付を表すテキストである理由は何ですか?アクセスには 'Date/Time'データ型があります。なぜそれを使わないのですか? – jmcilhinney

+0

データベースを制御できず、データをテキストとして受け入れる必要があると仮定すると、データベース内のそのテキストはどの形式ですか? – jmcilhinney

+0

また、これは狂っています: 'Dim currentDate As Date = Date.Now.ToString(" dd/MM/yyyy ")'。なぜ、 'Date'を' String'に変換し、それが暗黙的に 'Date'に変換されると思いますか?あなたが望むものが今日の日付であり、時刻がゼロであるならば、あなたは 'Date.Today'を使用していなければなりません。 – jmcilhinney

答えて

1

として 薄暗いEXPDATE表に

(ds.Tables("lecturer").Rows(i).Item(16)) 

をあなたの列の値を確認してください、私はあなたのことを考えます一致していない文字列を保存して日付に変換しました。

関連する問題