I have a program I am working on where all the events on given dates in a SQL DB populate a calendar. I recently switched from MYSQL to MSSQL 2012 and I am now getting the error "Conversion failed when converting date and/ or time from character string."
here is the code that forms the date
'// 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
The final Outcome is formatted yyyy-mm-dd. All future months work but it seems every 3rd month in the past does not.
The efficiency and security of your code notwithstanding, the obvious problem is that 5 of the 12 months do not have a 31st day and in these cases you are trying to assign dates that are invalid. VB knows how to count calendar units (e.g. months) properly when you use its methods, but assigning an invalid date from a string produces an error. Try this instead:
Dim endDate As DateTime = startDate.AddMonths(1).AddDays(-1)
Related
I have a public function (actually 2 that work together) that calculate working days. It works fine for ME, but everyone else gets 0 returned. I'm driving myself crazy trying to figure out why, why would this happen? They don't get an error, for May, they should get 21 and I do... but they just get 0.
Public Function Workdays(ByRef StartDate As Date, _
ByRef EndDate As Date, _
Optional ByRef strHolidays As String = "dbo_tblHolidays" _
) As Integer
' Returns the number of workdays between startDate
' and endDate inclusive. Workdays excludes weekends and
' holidays. Optionally, pass this function the name of a table
' or query as the third argument. If you don't the default
' is "dbo_tblHolidays".
On Error GoTo Workdays_Error
Dim nWeekdays As Integer
Dim nHolidays As Integer
Dim strWhere As String
' DateValue returns the date part only.
StartDate = DateValue(StartDate)
EndDate = DateValue(EndDate)
nWeekdays = Weekdays(StartDate, EndDate)
If nWeekdays = -1 Then
Workdays = -1
GoTo Workdays_Exit
End If
strWhere = "[fldHolidayDate] >= #" & StartDate _
& "# AND [fldHolidayDate] <= #" & EndDate & "#"
' Count the number of holidays.
nHolidays = DCount(Expr:="[fldHolidayDate]", _
Domain:=strHolidays, _
Criteria:=strWhere)
Workdays = nWeekdays - nHolidays
Workdays_Exit:
Exit Function
Workdays_Error:
Resume Workdays_Exit
Workdays = -1
MsgBox "Error " & Err.Number & ": " & Err.Description, _
vbCritical, "Workdays"
Resume Workdays_Exit
End Function
Public Function Weekdays(ByRef StartDate As Date, _
ByRef EndDate As Date _
) As Integer
' Returns the number of weekdays in the period from startDate
' to endDate inclusive. Returns -1 if an error occurs.
' If your weekend days do not include Saturday and Sunday and
' do not total two per week in number, this function will
' require modification.
On Error GoTo Weekdays_Error
' The number of weekend days per week.
Const ncNumberOfWeekendDays As Integer = 2
' The number of days inclusive.
Dim varDays As Variant
' The number of weekend days.
Dim varWeekendDays As Variant
' Temporary storage for datetime.
Dim dtmX As Date
' If the end date is earlier, swap the dates.
If EndDate < StartDate Then
dtmX = StartDate
StartDate = EndDate
EndDate = dtmX
End If
' Calculate the number of days inclusive (+ 1 is to add back startDate).
varDays = DateDiff(Interval:="d", _
date1:=StartDate, _
date2:=EndDate) + 1
' Calculate the number of weekend days.
varWeekendDays = (DateDiff(Interval:="ww", _
date1:=StartDate, _
date2:=EndDate) _
* ncNumberOfWeekendDays) _
+ IIf(DatePart(Interval:="w", _
Date:=StartDate) = vbSunday, 1, 0) _
+ IIf(DatePart(Interval:="w", _
Date:=EndDate) = vbSaturday, 1, 0)
' Calculate the number of weekdays.
Weekdays = (varDays - varWeekendDays)
Weekdays_Exit:
Exit Function
Weekdays_Error:
Weekdays = -1
MsgBox "Error " & Err.Number & ": " & Err.Description, _
vbCritical, "Weekdays"
Resume Weekdays_Exit
End Function
Compare your Regeional Settings with user PC's date formats.
Under Control Panel | Region and Language - compare Short and Long Date Format and see if they're the same as yours
I'm struggling with a problem about Dates manipulation.
Background :
Access 2013 - Classic Stock Table (id, name_item, record_date)
Currently working on SearchForm.
Have to finish the last filter (dates) - Others filters work.
I designed a ComboBox to filter "< 7 days", "< 30 days",...
PBM :
Date format is d/m/y (french format)
Operator < seems to compare with m/d/y even my date are defined in d/m/y.
I verified both Type in Table and Date(), they're set in d/m/y
CODE :
If InputDate.Value = "La semaine derniere" Then
strfilter = strfilter & "([Record_date] > #" & DateAdd("d", -7, Date) & "#)"
Debug.Print Month(DateAdd("d", -7, Date)) & " " & strfilter
Output :
9 ([Record_date] > #03/09/2015#)
I tried also strfilter = strfilter & "(Datediff('d', date(), [Record_date]) < 7)"
No difference :'(.
Any idea how I can go through this problem please.
Falt
You need the date value as a string expression formatted to yyyy/mm/dd:
strfilter = strfilter & "([Record_date] > #" & Format(DateAdd("d", -7, Date), "yyyy\/mm\/dd" & "#)"
So I'm making an application that gets all the events for a month out of a mysql DB and adds them to a calendar. I've got the events in a data table atm "dbTable"
The events are ascending by date
"SELECT * FROM table_events WHERE date BETWEEN '" & startDate & "' AND '" & endDate & "' ORDER BY date ASC"
Now I need to query each day one at a time to check for up to 6 events per date, any suggestions? Im not even sure on how to query the data table let alone do it for up to 31 days and make it somewhat efficient.
so after trying and reading i've figured it out. Thanks to all of you for your input.
Dim count As Integer
Dim expression As String
Dim foundRows() As DataRow
count = 0
expression = "date = '" & numericYear & "-" & doubleMonth & "-01'"
foundRows = dbTable.Select(expression)
For count = 0 To foundRows.Length - 1
'count = count + "1"
MessageBox.Show(dbTable.Rows(count).Item(5).ToString())
Next count
Where in this example numericYear = 2015 and doubleMonth = 06
Is it possible to convert date 4 digit year 2 digit month and 2 digit day to dd (3 digit month) 4 digit year?
Right now I have the input of date "use date" as user entered YYYYMMDD. I prefer to use the calendar input as it keeps the date consistent
A Date/Time value is actually a double precision float number.
So you can take a number, and use CDate to represent it as a date.
? CDate(41668.0)
1/29/2014
The display format of the date value is a separate issue. The same numeric date value can be displayed in whatever format you prefer.
? Format(CDate(41668.0), "yyyymmdd")
20140129
? Format(CDate(41668.0), "dd mmm yyyy")
29 Jan 2014
But the actual date value (the number) is unchanged --- that number doesn't get "converted" regardless of how it's displayed.
If your issue is that the users are working with a text value instead of a Date/Time value, you either have to convert that text to a valid Date/Time value or modify your application so they enter Date/Time values instead of text.
The second alternative is less fuss. But if you're stuck with dates as text, you can do something like this ...
use_date = "20140129"
' transform it to a string CDate can accept ...
? Left(use_date, 4) & "-" & Mid(use_date, 5, 2) & "-" & Right(use_date, 2)
2014-01-29
' get the date from that string ...
? CDate(Left(use_date, 4) & "-" & Mid(use_date, 5, 2) & "-" & Right(use_date, 2))
1/29/2014
' finally make it a string in your desired format ...
? Format(CDate(Left(use_date, 4) & "-" & Mid(use_date, 5, 2) & "-" & Right(use_date, 2)), "dd mmm yyyy")
29 Jan 2014
try
DIM DateStr : DateStr = "20140119" 'Your date
Response.Write "DEBUG: DateStr = " & DateStr & "<br>"
'Split number so can use Date functions
DIM NewDate : NewDate = DateSerial(CInt(Mid(DateStr, 1, 4)), CInt(Mid(DateStr, 5, 2)), Mid(DateStr, 7, 2))
Response.Write "DEBUG: NewDate = " & NewDate & "<br>"
TheDate=CDate(NewDate)
Response.Write "DEBUG: CDate(NewDate) = " & TheDate & "<br>"
DIM FinalDate: FinalDate = DatePart("d", TheDate) & " "
FinalDate = FinalDate & MonthName(Month(TheDate),1) & " "
FinalDate = FinalDate & DatePart("yyyy", TheDate)
Response.write "DEBUG: Required Date = " & FinalDate
I have two datetimepicker, startDate is stored datetimepicker1 value and endDate is stored datetimepicker2 value.
I want to to get the data between startDate and endDate from database.
Dim bSql As String = "select date, sum(total_price) from bill where Date = '" & Format(startDate, "yyyy/MM/dd") & " and Date='" & Format(endDate, "yyyy/MM/dd") & "'"
i tried the code above but it can't work. Anyone can help me?
If you're trying to find a string format for a date at all, you've already lost. Try this:
Dim bSql As String = "select date, sum(total_price) from bill where Date >= #startDate and Date < #endDate;"
Using cn As New MySqlConnection("connection string here"), _
cmd As New MySqlCommand(bSql, cn)
cmd.Parameters.Add("#startDate", SqlDbType.DateTime).Value = startDate
cmd.Parameters.Add("#endDate", SqlDbType.DateTime).Value = endDate.AddDays(1)
cn.Open()
'...
End Using
No formatting required or wanted.
Try this, using the SQL BETWEEN operator, which allows you to specify the lower and upper bounds of a range.
Dim bSql As String = "select date, sum(total_price) from bill where Date BETWEEN '" & startDate.ToString("yyyy/MM/dd") & "' AND '" & endDate.ToString("yyyy/MM/dd") & "' GROUP BY date;"
You will also need to apply a grouping to use the aggregate function "SUM":
-- find all dates with sales and the total prices on each date
SELECT [date], SUM(total_price) AS [TotalPrice]
FROM bill
WHERE [date] BETWEEN '2013-01-01' AND '2013-12-31' -- use appropriate date format here
GROUP BY [date];
in data base i have DD/MM/YYYY
solution is to make in VB MM/DD/YYYY
this is a CODE
oldbc.CommandText = "select * from recette where Date between #10/09/2015# and #10/011/2015#"
Try formatting your dates like this (you will need to use the Value of the DateTimePicker as well):
Format(startDate.Value, "yyyy-MM-dd")
A better option is to use a parameterised query and then you don't have to format the date into any particular format. More info here: How do I create a parameterized SQL query? Why Should I?
Dim bSql As String = "select date, sum(total_price) from bill where Date = " & DateTimePicker1.Text & " and Date=" & DateTimePicker1.Text & ""
Set the datetime picker date format.
I hope it will helpful for you...
Another possibility is to make a little function to format DATE variable and return correct date string syntax for MySQL.
Public Function MySQLDate(inDate As Date) As String
Return "'" & inDate.ToString(format:="yyyy'/'MM'/'dd") & "'"
End Function
Now your query is more readable, easier to create, and looks like this:
Dim bSql As String = "select date, sum(total_price) from bill where Date BETWEEN " & MySQLDate(startDate) & " and " & MySQLDate(endDate)