2015-10-04 73 views
0

我在窗體上使用DatePicker和textfield來選擇日期,默認情況下它會在文本字段中顯示爲dd/mm/yyyy。因此,當我編寫我的代碼時,我使用這種格式來保持一致。但是當我保存一個像03/10/2015(這是十月的第三天)的日期時,它將被保存爲3月10日。鑑於下面的代碼,我需要改變什麼才能正確保存到數據庫?將日期和月份保存到數據庫時反轉

Private Sub cmdSave_Click() 
    ... 
    Dim StartDate As String 
    Dim EndDate As String 
    Dim SDate As Date 
    Dim EDate As Date 
    ... 
    StartDate = Me.txtStartDate.Value & " " & Me.txtStartTime.Value 
    EndDate = Me.txtEndDate.Value & " " & Me.txtEndTime.Value 
    SDate = CDate(Format(StartDate, "dd\/mm\/yyyy hh:mm")) 
    EDate = CDate(Format(EndDate, "dd\/mm\/yyyy hh:mm")) 

    If Me.txtOtherDetails.Value = "" Then 
    query1 = "INSERT INTO Shifts (Schedule_ID,Start_Date_Time,End_Date_Time,Location)" & _ 
    " VALUES (" & ScheduleID & ",#" & SDate & "#,#" & EDate & "#," & LocationID & ")" 
    Else 
    query1 = "INSERT INTO Shifts (Schedule_ID,Start_Date_Time,End_Date_Time,Location,Other_Details)" & _ 
    " VALUES (" & ScheduleID & ",#" & SDate & "#,#" & EDate & "#," & LocationID & ",'" & Me.txtOtherDetails.Value & "')" 
    End If 

    'Debug.Print query1 
    ShiftID = ExecuteInsert(query1) 
End Sub 

回答

1

你應該在查詢日期的格式更改爲mm/dd/yyyy,因爲這是在MS Access查詢使用的format。 所以你應該改變:

SDate = CDate(Format(StartDate, "mm\/dd\/yyyy hh:mm")) 
EDate = CDate(Format(EndDate, "mm\/dd\/yyyy hh:mm")) 
+0

你的建議的工作。謝謝。 – Alan

1

這已經完全混淆了。

如果你的文本框已經被應用的日期/時間格式,他們將舉行日期值有效的日期表達式,而這些必須進行格式化,以有效字符串表達式與SQL代碼來串聯。

此外,串聯的日期/時間值與SQL將使用默認的Windows設置,這將在美國以外的環境中失敗的1號的日期最初迫使值的強制轉換爲字符串12。

因此,這是所有你需要:

Private Sub cmdSave_Click() 
    ... 
    Dim StartDate As String 
    Dim EndDate As String 
    ... 
    StartDate = Format(Me!txtStartDate.Value & " " & Me!txtStartTime.Value, "yyyy\/mm\/dd hh\:nn") 
    EndDate = Format(Me!txtEndDate.Value & " " & Me!txtEndTime.Value, "yyyy\/mm\/dd hh\:nn") 

    If Me!txtOtherDetails.Value = "" Then 
    query1 = "INSERT INTO Shifts (Schedule_ID,Start_Date_Time,End_Date_Time,Location)" & _ 
    " VALUES (" & ScheduleID & ",#" & StartDate & "#,#" & EndDate & "#," & LocationID & ")" 
    Else 
    query1 = "INSERT INTO Shifts (Schedule_ID,Start_Date_Time,End_Date_Time,Location,Other_Details)" & _ 
    " VALUES (" & ScheduleID & ",#" & StartDate & "#,#" & EndDate & "#," & LocationID & ",'" & Me!txtOtherDetails.Value & "')" 
    End If 

    'Debug.Print query1 
    ShiftID = ExecuteInsert(query1) 
End Sub 
相關問題