保存到数据库时,日期和月份相反

时间:2015-10-04 18:01:44

标签: access-vba ms-access-2010 dao

我在表单上使用DatePicker和textfield供用户选择日期,默认情况下它在文本字段中显示为dd / mm / yyyy。因此,当我编写代码时,我使用这种格式保持一致。但是当我保存像2015年10月3日(即10月的第3天)的日期时,它将保存为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

2 个答案:

答案 0 :(得分: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"))

答案 1 :(得分: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