I'm using this code to get the last number in a column where date of column is today date:
cn.Open("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & Application.StartupPath & "\bysys.mdb")
rs.Open("Select max(snum) From tblbill where idate = #" & Format(Today.Date, "dd/MM/yyyy") & "# ", cn, 1, 2)
If IsDBNull(Rs.Fields(0).Value) Then
TextBox6.Text = 1
Else
TextBox6.Text = Rs.Fields(0).Value + 1
End If
Sometimes it works correctly, but sometimes, it always return 1..
When you submit a value which can represent a valid date in mm/dd/yyyy format, Access will interpret it as such. You could deliberately format it as mm/dd/yyyy instead of dd/mm/yyyy. But many of us prefer yyyy/mm/dd because Access always interprets that format correctly and we humans needn't be bothered about possible confusion over whether the date is dd/mm/yyyy or mm/dd/yyyy format.
"Select max(snum) From tblbill where idate = #" & Format(Today.Date, "yyyy/mm/dd") & "# "
However the db engine supports a function, Date(), which your query can use to refer to the current date without bothering about any formatting. So this alternative seems simplest to me ...
"Select max(snum) From tblbill where idate = Date()"
Related
My computer's regional date setting is dd/mm/yyyy. I am using MS Access. I would like to insert records into a database using the SQL INSERT INTO statement. When I try to insert a date using the #dd/mm/yyyy# syntax, and view the resulting record in the table after, it turns out the record displays the date in the format mm/dd/yyyy instead, but ONLY for the first 10 days of the month; if the day is 11 onwards, the record displays dd/mm/yyyy as intended.
For example if in SQL code I input #09/02/2022#, the table will display the record with the date 02/09/2022 instead. However if my SQL code is#11/02/2022#, then the correct order 11/02/2022 is shown in the record.
Please help.
Ok, the way this works?
You don't have to care, know, or think about the users regional format settings.
So, if you drop some control on a form? Just make sure that control is set to a date type format. Your done.
BUT ONE big whopper:
IN ANY AND ALL cases, your string based date format MUST be in USA format. Or you can use ISO date format.
dim MyDate as Date
MyDate = me.InvoiceDate
So, now we have a internal format date variable. How to insert into a table?
dim strSQL as string
strSQL = "INSERT INTO tblInvoice (InvoiceNum, InvoiceDate, InvoiceAmount " & _
"VALUES (1234, " & quDate(MyDate) & ",50)"
So, you ALWAYS format the date value into USA format.
You can type that format command over and over, but that fast becomes tiring.
so, I use a little helper function:
Public Function quDate(dt As Date) As String
quDate = "#" & Format(dt, "mm\/dd\/yyyy") & "#"
End Function
Public Function quDateT(dt As Date) As String
' return formatted date with time
quDateT = "#" & Format(dt, "mm\/dd\/yyyy HH:NN:SS") & "#"
End Function
So, you don't have to care about the date and regional format, but for a in-line SQL insert command that you build in code? Yes, you MUST convert to USA format of mm/dd/yyyy.
So, you can display dates in any format. For forms, for reports - not a problem.
However, the ONLY exception here is your code that builds a insert statement. That date string format must be #mm/dd/yyyy#.
Or, ISO:
#yyyy-mm-dd#
So, either format is fine, but it is a hard and fast rule that you must conform to.
So, from a text box on a form, if not data bound, then you want to ensure that the text box is set as a date type text box (fomrat date).
then in code:
dim strSQL as string
strSQL = "INSERT INTO tblFun (BirthDate) " & _
"VALUES (#" & format(txtDate,"mm/dd/yyyy") & "#)"
currentdb.Execute strSQL
Or, if you have that helper function, then this:
strSQL = "INSERT INTO tblFun (BirthDate) " & _
"VALUES (" & qudate(txtDate) & ")"
I have a report which contains a datetime field. There is a form used to gather user input for the query, specifically the From and To date for the query to be filtered.
The report is opened using this code:
Dim str as String
str = "DateCreated BETWEEN #" & format(From_Date.value, "yyyy-mm-dd") & "# AND #" & DateAdd("d", 1, format(To_Date.value, "yyyy-mm-dd")) & "#"
DoCmd.OpenReport "report_name", acViewReport, WhereCondition:=str
On Windows machines that have the date format as mm/dd/yyyy, or yyyy-mm-dd, the query works.
Some users have the system date set to dd/mm/yyyy. The filter is reading 08/11/2021 (Nov 8th, 2021) as Aug 11th, 2021.
I tried formatting the date inputs for the WHERE condition using format(From_Date.value, "yyyy-mm-dd").
Does Access support dd/mm/yyyy format? How can I filter by a date range?
Is the only option to adjust the user's system date format?
Always use parameters, never concatenate formatted dates to SQL strings.
If you use formatted dates in SQL strings you're setting yourself up for failure, the chance of accidentally doing something wrong is huge.
Dim str as String
str = "DateCreated BETWEEN p1 AND p2"
DoCmd.SetParameter "p1", From_Date.value
DoCmd.SetParameter "p2", DateAdd("d", 1, To_Date.value)
DoCmd.OpenReport "report_name", acViewReport, WhereCondition:=str
Read more on parameters in Access: How do I use parameters in VBA in the different contexts in Microsoft Access?
You can use one of the general date format codes (instead of a custom format string) to use the system format.
Dim str as String
str = "DateCreated BETWEEN #" & format(From_Date.value, "Long Date") & "# AND #" & DateAdd("d", 1, format(To_Date.value, "Long Date")) & "#"
DoCmd.OpenReport "report_name", acViewReport, WhereCondition:=str
I have a table of whose rows contain a date/time filled with appointment times. The appointment times are a single field (i.e. the date and the time together). I've created a recordset to fetch all the appointments which occur on a given date:
Dim dt as date
dt = #3/2/2019#
Set rs = Currentdb.OpenRecordSet("SELECT stuff FROM Appt WHERE
Int(Appt.apptTime) = #" & dt & "#") --------
This works, but the "Int" function makes it inefficient. One solution would be to separate the date/time field into two fields (date and time) then just search on the date field. Unfortunately, I don't have the option of modifying the database structure.
Does anyone have a suggestion of how I can make this fetch more efficient?
You must format the date expressions properly and remember the equal option:
Set rs = Currentdb.OpenRecordSet("SELECT stuff FROM Appt WHERE Appt.apptTime >= #" & Format(dt, "yyyy\/mm\/dd") & "# AND Appt.apptTime < #" & Format(DateAdd("d", 1, dt), "yyyy\/mm\/dd") & "#")
I just figured out a solution:
WHERE (Appt.apptTime > #" & dt & "#) AND (Appt.apptTime < #" & dt + 1 & "#")
You can use DateValue(Appt.apptTime)
eg:
"WHERE ( DateVaue(Appt.apptTime) = #" & dt & "#"
The above will return only the date part and remove the time portion.
However, the above can't use high-speed indexing. So, your follow answer of :
WHERE (Appt.apptTime > #" & dt & "#) AND (Appt.apptTime < #" & dt + 1 & "#")
will run much faster. The only other issue is that you should (need) to force the format to USA format, else your posted solution can fail depending on the users reginal (date format) settings. So, on some computer you find the above will not work, or fail, or even get things like 4/5/2020 mixed up. Is that April 5, or May 4th?
So, you need to correctly format the date to USA and ensure that you IGNORE the users date format, else your code will fail on many computers with different date formats.
You should create a helper function for this, like this:
Public Function quDateT(dt As Date) As String
' return formatted date
quDateT = "#" & Format(dt, "mm\/dd\/yyyy HH:NN:SS") & "#"
End Function
Then, your query becomes:
WHERE (Appt.apptTime > " & qudateT(dt) & ") AND (attt.apptTime < " & qudateT(dt + 1)
Now in your case, DT will not have time, so the time portion of qudateT will be 00:00:00.
So, your example follow up should work, but you want to FORCE the date format to MM/DD/YYYY (USA) format, and if users have their setting such as DD/MM/YYYY, then your example query will fail on computers with such (different) regional settings.
I don't see why date formatting matter as all dates, regardless of displayed format, are stored as double-precision, floating-point numbers. The integer portion being the number of days since December 30, 1899; the fractional portion being the fraction of the 24-hour day. So my computation (in my updated "found a solution" post), which treats the dates as numbers should be immune to whatever date format has been chosen for the display of dates, right?
I am creating a simple database for tracking working hours. The idea is that:
Every day you need to input only the days that employee did not work (startDate, endDate, absenceType),
Then calculate working days for the whole month or selected period.
Calculation of working days should take into account weekends (saturday, sunday) and holidays from Holiday table.
I took a function sample from MSDN (Counting the Number of Working Days in Access 2007) and put it into a module in my MS Access 2010 db but each time I run a query I have this error.
Typically the same error appears attempting to run a query in another sample database from somewhere.
The problem is in the strWhere clause:
strWhere = "[Holiday] >=#" & startDate & "# AND [Holiday] <=#" & endDate & "#"
' Count the number of holidays.
nHolidays = DCount(Expr:="[Holiday]", Domain:=strHolidays, Criteria:=strWhere)
Workdays = nWeekdays - nHolidays
The error msg from both databases is available in the link below
Runtime Error 3075 Syntax error in date in query expression
Any help is appreciated.
You must force a format on the string expressions for your dates. Get used to use the ISO sequence yyyy-mm-dd as it works everywhere:
strHolidays = "NameOfYourTable"
strWhere = "[Holiday] >= #" & Format(startDate, "yyyy\/mm\/dd") & "# AND [Holiday] <= #" & Format(endDate, "yyyy\/mm\/dd") & "#"
' Count the number of holidays.
nHolidays = DCount("*", strHolidays, strWhere)
In the past I have had issues where VBA doesn't always respect the regional date settings. Try forcing it into US format before concatenating it
strWhere = "[Holiday] >=#" & Format(startDate, "MM/dd/yyyy") & "# AND [Holiday] <=#" & Format(endDate, "MM/dd/yyyy") & "#"
Make sure the date is in MM/DD/YYYY order in VBA. Always. I generally use:
strWhere = "[Holiday] >= " & Format(startDate,"\#mm\/dd\/yyyy\#")
the second argument of DCount is strHolidays. That does not look like the name of a table/query. This argument should be the name of a table/query.
somebody help me with the problem that every time i save or update a data the date is working fine but the time is always 12:00AM. the time should be the time when I input the data and be saved into the database.
this is my code for the update
Dim i As Short
con.Open()
Using com As New SqlClient.SqlCommand("UPDATE Information set FiveS_Date = '" & DateTimePicker1.Text & "',FiveS_Score = '" & TextBox2.Text & "',FiveS_Total = '" & TextBox3.Text & "' ,FiveS_Percentage = '" & TextBox4.Text & "' WHERE Id='" & id & "'", con)
i = com.ExecuteNonQuery()
End Using
con.Close()
If (i > 0) Then
MsgBox("Training updated successfully", MsgBoxStyle.Information)
End If
please help.
You should use parameters to avoid the problem of data conversion when you use ADO.NET. This helps you also with different cultures in your application.
Anyway, DateTimePicker1.Valuewill give you also the time, but if you select a date which is different from default value of DateTimePicker (which is Now), then DateTimePicker will always give you the time "12:00". You have to format it to show time also and to have the possibility to set it (example "MM/dd/yyyy HH:mm").
Try changing DateTimePicker1.Text to DateTimePicker1.Value.ToString
.Text just returns what is visible (date only) whereas .Value returns the current time as well as the date displayed.
Try this :
FiveS_Date ='" + DateTime.Parse(datetxt.Text).ToString("dd/MM/yyy") +"'
For starters, DateTimePicker1.Text will only give you the String that is displayed in the DateTimePicker, by default the DateTimePickers format will only show you the Date and by default the time will be 12:00 AM. You can change the DateTimePicker format to show time by changing the Format field in the Properties Window of the DateTimePicker to Time.
DateTimePicker to Time format
Or by your sentence you want to save the date selected combined with the time you saved the data to the database, just make a new DateTime variable and insert the DateTimePicker Dates as values to that variable and the time from DateTime.Now() function which will return the current date and time.
Dim now As DateTime = DateTime.Now()
Dim myDate = new DateTime(DateTimePicker1.Value.Year, DateTimePicker1.Value.Month, DateTimePicker1.Value.Day, now.Hour, now.Minute, now.Second, now.Millisecond)
To insert time into database you need to use
DateTimePicker1.Value
instead of
DateTimePicker1.Text