【问题标题】:day and month reversed when saving to database保存到数据库时反转日期和月份
【发布时间】:2015-10-04 18:01:44
【问题描述】:

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

【问题讨论】:

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


    【解决方案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"))
    

    【讨论】:

      【解决方案2】:

      这完全搞混了。

      如果您的文本框应用了日期/时间格式,它们将保存日期值的有效日期表达式,并且这些必须格式化为有效的 string 表达式才能与 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
      

      【讨论】:

        猜你喜欢
        • 2012-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多