> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/pocketbase/pocketbase/llms.txt
> Use this file to discover all available pages before exploring further.

# Autodate field

> Automatically set timestamps on record create and/or update

The autodate field automatically sets the current date and time when records are created or updated. It's commonly used for `created` and `updated` timestamp fields.

## Configuration options

<ParamField path="onCreate" type="bool" default="false">
  When true, automatically sets the current datetime when the record is created.
</ParamField>

<ParamField path="onUpdate" type="bool" default="false">
  When true, automatically updates to the current datetime whenever the record is updated.
</ParamField>

<Warning>
  At least one of `onCreate` or `onUpdate` must be enabled. Both can be enabled simultaneously.
</Warning>

## How it works

The autodate field has special behavior:

1. **Automatic setting**: The value is automatically set during create/update operations
2. **Read-only via Set()**: Calling `record.Set()` on an autodate field has no effect
3. **Manual override**: You can manually set values using `record.SetRaw()` if needed
4. **System fields**: If the field is marked as `system`, the `onCreate` and `onUpdate` settings cannot be changed

<Info>
  The autodate field uses a no-op setter, which means `record.Set()` calls are ignored. Use `record.SetRaw()` if you need to manually override the timestamp.
</Info>

## Go examples

<Tabs>
  <Tab title="Created timestamp">
    ```go theme={null}
    import "github.com/pocketbase/pocketbase/core"

    field := &core.AutodateField{
        Name:     "created",
        OnCreate: true,
        OnUpdate: false,
    }

    collection.Fields.Add(field)

    // Value is automatically set on create
    record := core.NewRecord(collection)
    app.Save(record)
    // created field now contains the current timestamp
    ```
  </Tab>

  <Tab title="Updated timestamp">
    ```go theme={null}
    field := &core.AutodateField{
        Name:     "updated",
        OnCreate: true,  // Set on create
        OnUpdate: true,  // Update on every save
    }

    collection.Fields.Add(field)

    // On create: both created and updated are set
    record := core.NewRecord(collection)
    app.Save(record)

    // On update: only updated is modified
    record.Set("title", "New Title")
    app.Save(record)
    // updated field is refreshed to current timestamp
    ```
  </Tab>

  <Tab title="Manual override">
    ```go theme={null}
    import "github.com/pocketbase/pocketbase/tools/types"

    field := &core.AutodateField{
        Name:     "publishedAt",
        OnCreate: true,
        OnUpdate: false,
    }

    collection.Fields.Add(field)

    record := core.NewRecord(collection)

    // This has no effect (field is autodate)
    record.Set("publishedAt", types.NowDateTime())

    // Use SetRaw to manually override
    customDate, _ := types.ParseDateTime("2024-01-15 10:00:00.000Z")
    record.SetRaw("publishedAt", customDate)

    app.Save(record)
    // publishedAt will use the custom date
    ```
  </Tab>

  <Tab title="Both create and update">
    ```go theme={null}
    field := &core.AutodateField{
        Name:     "lastModified",
        OnCreate: true, // Set on create
        OnUpdate: true, // Update on every save
    }

    collection.Fields.Add(field)

    // Always reflects the last modification time
    ```
  </Tab>
</Tabs>

## Database column type

```sql theme={null}
TEXT DEFAULT '' NOT NULL
```

<Info>
  Autodate fields store timestamps as ISO 8601 formatted strings, the same as regular date fields.
</Info>

## Common patterns

<CodeGroup>
  ```go Standard timestamps theme={null}
  // Created timestamp (set once)
  collection.Fields.Add(&core.AutodateField{
      Name:     "created",
      OnCreate: true,
      OnUpdate: false,
  })

  // Updated timestamp (always current)
  collection.Fields.Add(&core.AutodateField{
      Name:     "updated",
      OnCreate: true,
      OnUpdate: true,
  })
  ```

  ```go Published date theme={null}
  // Tracks when content was published
  field := &core.AutodateField{
      Name:     "publishedAt",
      OnCreate: false,
      OnUpdate: false,
  }
  // Must be set manually with SetRaw
  ```

  ```go Last accessed theme={null}
  field := &core.AutodateField{
      Name:     "lastAccessed",
      OnCreate: true,
      OnUpdate: true, // Updates every time record is touched
  }
  ```
</CodeGroup>

## System fields

Base collections automatically include autodate system fields:

```go theme={null}
// These are automatically added to every collection
&AutodateField{
    Name:     "created",
    System:   true,
    OnCreate: true,
    OnUpdate: false,
}

&AutodateField{
    Name:     "updated",
    System:   true,
    OnCreate: true,
    OnUpdate: true,
}
```

<Warning>
  System autodate fields cannot have their `onCreate` or `onUpdate` settings changed to maintain consistency across all PocketBase collections.
</Warning>

## Reading autodate values

<CodeGroup>
  ```go Get as DateTime theme={null}
  import "github.com/pocketbase/pocketbase/tools/types"

  created := record.GetDateTime("created")
  updated := record.GetDateTime("updated")

  // Check if set
  if !created.IsZero() {
      // Has a value
  }
  ```

  ```go Get as time.Time theme={null}
  created := record.GetDateTime("created").Time()

  // Calculate time since creation
  import "time"
  age := time.Since(created)
  ```

  ```go Get as string theme={null}
  createdStr := record.GetString("created")
  // "2024-03-15 14:30:00.000Z"
  ```
</CodeGroup>

## Filtering by autodate fields

<CodeGroup>
  ```go Recent records theme={null}
  import "time"
  import "github.com/pocketbase/pocketbase/tools/types"

  // Records created in the last 24 hours
  last24h := types.DateTime{Time: time.Now().Add(-24 * time.Hour)}
  records, err := app.FindRecordsByFilter(
      "articles",
      "created > {:date}",
      "-created",
      10,
      0,
      dbx.Params{"date": last24h},
  )
  ```

  ```go Modified since theme={null}
  // Records updated after a specific date
  records, err := app.FindRecordsByFilter(
      "articles",
      "updated > '2024-01-01 00:00:00.000Z'",
      "-updated",
      10,
      0,
  )
  ```
</CodeGroup>

## Use cases

<Note>
  **When to use onCreate only:**

  * Tracking creation timestamp (standard `created` field)
  * Recording when content was first published
  * Audit trail: when a record was first inserted

  **When to use onUpdate only:**

  * Tracking last modification (when you don't care about creation)
  * Cache invalidation timestamps

  **When to use both:**

  * Standard `updated` field that needs an initial value
  * Activity tracking that should always show last interaction
  * Last accessed/viewed timestamps
</Note>

## Best practices

<Note>
  * Use the standard `created` and `updated` system fields when possible
  * Only create additional autodate fields when you need specific behavior
  * Remember that `record.Set()` doesn't work on autodate fields
  * Use `SetRaw()` for manual overrides (like backdating records)
  * Consider using regular date fields if you need user-controllable dates
  * Autodate fields are always in UTC
</Note>

## Comparison with date field

| Feature                | Autodate            | Date             |
| ---------------------- | ------------------- | ---------------- |
| Automatic setting      | Yes                 | No               |
| Can use `record.Set()` | No (use `SetRaw()`) | Yes              |
| Validation             | None                | Min/Max/Required |
| Use case               | Timestamps          | User input dates |

## Zero value

The zero value for autodate fields is a zero `types.DateTime`, but in practice autodate fields are typically always set automatically.
