Wednesday, January 25, 2012

Now() Function in Default Value Stores the Wrong Time

In a previous post (Date Stuff – Using the functions), I discussed, among other things, using built in Access functions (specifically Date() and Now()) in the default value of a field in a table.

The Date() function is generally safe to use, but the Now() function is problematic. Now() in the default value of your field WILL store the wrong time. If your concern is to store an accurate time of when the record was saved, this is a problem.

Let me illustrate.  Suppose I have a simple table like so:


Now, I'm going to add a field called CreatedDate, and use the Now() function in the Default Value of the field.


The New Record, that is, the one at the bottom with the asterisk at the far left, has not yet been created.  The date and time displayed is the time that I opened the table (or form, if the form was based on that table). 

However, suppose I take a few minutes before I actually enter anything into the new record.


Once I begin typing in the record, it is created (but not yet saved), but notice that the time that I opened the table is still displayed, even though the actual time (as shown in the task bar) is 6 minutes later.

By the time I get around to actually saving the record (by moving to the new New Record) another 5 minutes has passed.


So the record was saved at 6:29, but the time stored in the field is 6:18.  Not only that, but the next New Record displays the time that the previous record was created.


So what do you do to get an accurate time in the CreatedDate field?  There are two solutions depending on which version of Access you're using: Access 2007 (and previous) or Access 2010.

Access 2007 and Previous

In Access 2007 and before, it cannot be done at the table level.  It must be done in a form.  So in Design View of your form, create a code procedure in the BeforeUpdate Event of the form:


Private Sub Form_BeforeUpdate(Cancel As Integer)
    If IsNull(CreatedDate) Then
        CreatedDate = Now()
    End If
End Sub

Access 2010

With the introduction of Access 2010, we how have Data Macros (essentially triggers) that work at the table level.


On the Tables tab, select the Before Change Event and create the following data macro:


Now, you will save the actual time the record was saved.

No comments: