我正在处理一个程序,其中SQL DB中给定日期的所有事件都填充日历。我最近从MYSQL切换到MSSQL 2012,现在我收到错误"Conversion failed when converting date and/ or time from character string."
这是形成日期的代码
'// Set Start and End Date
If numericMonth < 10 Then
doubleMonth = "0" & numericMonth 'If Month was September doubleMonth = 09
startDate = numericYear & "-" & doubleMonth & "-01" ' If date was June 1 2015 startdate would = 2015-06-01
Calendar1.Refresh()
Else
startDate = numericYear & "-" & numericMonth & "-01"
doubleMonth = numericMonth
End If
Dim endDate As String
If numericMonth < 10 Then
endDate = numericYear & "-0" & numericMonth & "-31"
Else
endDate = numericYear & "-" & numericMonth & "-31" ' If date was June 30 2015 enddate would = 2015-06-31
End If
If bypassMode = "0" Then
count = 0
dbQuery = "SELECT * FROM SOEVENTS WHERE DATE BETWEEN '" & startDate & "' AND '" & endDate & "' ORDER BY date ASC"
If SQL.HasConnection = True Then
SQL.RunQuery(dbQuery)
End If
最终的结果格式为yyyy-mm-dd。所有未来的月份都会有效,但似乎过去每隔3个月都没有。
答案 0 :(得分:0)
尽管代码的效率和安全性,但显而易见的问题是,12个月中有5个月没有第31天,在这种情况下,您尝试分配无效的日期。 VB知道如何在使用其方法时正确计算日历单位(例如月份),但从字符串中指定无效日期会产生错误。试试这个:
Dim endDate As DateTime = startDate.AddMonths(1).AddDays(-1)