Date Format changes when inserting into table if start date and end date cross one or more months

◇◆丶佛笑我妖孽 提交于 2019-12-06 14:23:24

问题


I have an Access 2013 form which has two unbound date fields, FromDate and ToDate. I insert these into a table (TblGuestBooking) which has an autonumber key field, so this doesn't feature in the SQL statement to follow.

If the FromDate and ToDate are in the same month, the dates are entered as dd/mm/yy, the format of the form field. If, however, the From date is in one month and the to date is in the next month or later month, the format changes to mm/dd/yy for the subsequent months.

for example 26/2/14 to 3/3/14 results in the following table entries:

26/02/14,
27/02/14,
28/02/14,
03/01/14,
03/02/14,
03/03/14

This is the code snippet I am using to put the dates into the table (BookingID is obtained from the form.)

Dim BookingDate As Date

Dim SQLString As String

....

BookingDate = FromDate

Do
    SQLString = "INSERT INTO TblGuestBooking ([BookingDate], [BookingID])  VALUES (#" & BookingDate & "#" & "," & Me.GuestSuiteBookingID & ")"

    DoCmd.SetWarnings False
    DoCmd.RunSQL SQLString
    DoCmd.SetWarnings True
    BookingDate = BookingDate + 1
Loop Until BookingDate = ToDate + 1

If you've read this far, thank you for your time. If you can help me out, many, many thanks.


回答1:


When processing date literals (text values enclosed by "hash marks" #) Access SQL will always interpret ambiguous xx-yy-zzzz dates as mm-dd-yyyy, regardless of the regional setting in place on the computer. So, if your machine is configured to display short dates as dd-mm-yyyy and you create an Access query that uses #04-02-2014# it will always be interpreted as April 2, not February 4.

The solution is to always format date literals as unambiguous yyyy-mm-dd values. In your case, instead of

... VALUES (#" & BookingDate & "#" ...

you would use something like

... VALUES (#" & Format(BookingDate, "yyyy-mm-dd") & "#" ...



回答2:


In my case I've used following code for an ASP page that create and update a Date field in Access database.

strDay = Request("Day")
strMonth = Request("Month")
strYear = Request("Year")

InputDate =  strYear & "-" & strMonth & "-" & strDay
if IsDate(InputDate) Then
    InsertDate = CDate(InputDate)
else
'if date typed wrong, use Todays Date
    InsertDate = Date()
end if

SQLUPD = "UPDATE MyDataBase SET DateField = '"& FormatDateTime(InsertDate, vbShortDate) &"'"
SQLINS = "INSERT INTO MyDataBase (DateField, Alist, Atype, Acomment) VALUES ('"& FormatDateTime(InsertDate, vbShortDate) &"', .....

Then all sorting and output opration with dates are going well.



来源:https://stackoverflow.com/questions/21714445/date-format-changes-when-inserting-into-table-if-start-date-and-end-date-cross-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!