Display SQL time field on Access form as Access medium time hh:mm am/pm

前端 未结 2 1986
清酒与你
清酒与你 2021-01-26 20:08

I am using Access 2010 linked to SQL Server 2008 R2. My problem - how do I display time on an Access form as hh:mm am/pm instead of SQL Server\'s time(7) format of

相关标签:
2条回答
  • 2021-01-26 20:25

    Sorry, I don't have a dev environment setup, but can you change your SQL query to:

    SELECT Convert(varchar(5), getdate(), 108) 
    

    to give HH:MM and truncate the rest so it displays correctly.

    Then, you can cast as date on the way back.

    0 讨论(0)
  • 2021-01-26 20:28

    Access doesn't have a Time data type, so when it links to a SQL Server time column it maps that column as Text. That's why any Date/Time Format specifier you try to apply to the linked table value has no effect: as far as Access is concerned it's a string.

    So if we have a SQL Server table [Appointments]:

    sqlTable.png

    and we create a Linked Table in Access we get

    accessTable.png

    If we create an Access form for that linked table and use plain old bound controls we get this

    form1.png

    The text box for [apptStart] does work, but it doesn't look so great. The workaround is to leave that text box on the form, but hide it (set its .Visible property to No) and then add another unbound text box to the form. (In this case I called it [txtStartTime].) Set the .Format of the new text box to Medium Time and adjust any other formatting as required (e.g., I set Text Align to Left).

    In the On Current form event, calculate the Access Date/time value corresponding to the start time in SQL Server table and stuff that value into the [txtStartTime] text box. Now we get something that looks a little better:

    form2.png

    Now what if the user wants to edit that value? In the After Update event for the [txtStartTime] text box we create the corresponding SQL Server time string and stuff that value into the (invisible, bound) [apptStart] text box. When the record is saved the new time value is updated in the SQL Server table.

    The code behind the form is as follows:

    Option Compare Database
    Option Explicit
    
    Const accessDate0 = "1899-12-30 " ' <- note trailing space
    Dim startTimeAsDateTime As Date
    
    Private Sub Form_AfterUpdate()
        Me.Requery
    End Sub
    
    Private Sub Form_Current()
        Me.txtStartTime.Value = CDate(accessDate0 & Left(Me.apptStart, 8))
    End Sub
    
    Private Sub txtStartTime_AfterUpdate()
        Me.apptStart.Value = Format(startTimeAsDateTime, "hh:nn:ss")
    End Sub
    
    Private Sub txtStartTime_BeforeUpdate(Cancel As Integer)
        On Error GoTo txtStartTime_BeforeUpdate_Error
        startTimeAsDateTime = CDate(accessDate0 & Me.txtStartTime.Value)
        Exit Sub
    
    txtStartTime_BeforeUpdate_Error:
            MsgBox "Start Time appears to be invalid."
            Cancel = True
    End Sub
    
    0 讨论(0)
提交回复
热议问题