Skip to content

Conversation

Copilot
Copy link
Contributor

@Copilot Copilot AI commented Sep 20, 2025

The datatypes.Date type was incorrectly handling timezones when using PostgreSQL with PreferSimpleProtocol: true, causing dates to be stored as the previous day.

Problem

When using postgres.Config{PreferSimpleProtocol: true}, the datatypes.Date would send the wrong date to the database. For example:

db, err := gorm.Open(postgres.New(postgres.Config{
    PreferSimpleProtocol: true,
    DSN: "...",
}), &gorm.Config{})

// This would insert 2025-09-17 instead of 2025-09-18
err := db.Create(&Model{
    Id:   10,
    Date: datatypes.Date(time.Now()), // 2025-09-18
}).Error

The debug log would show the correct date, but the actual value inserted would be the previous day.

Root Cause

The issue was in the Date.Value() method, which preserved the original timezone of the input time:

func (date Date) Value() (driver.Value, error) {
    y, m, d := time.Time(date).Date()
    return time.Date(y, m, d, 0, 0, 0, 0, time.Time(date).Location()), nil
}

When PostgreSQL uses simple protocol mode, timezone-aware dates can be interpreted incorrectly, especially when the original time is in a timezone ahead of UTC.

Solution

Changed the Date.Value() method to always return dates in UTC timezone:

func (date Date) Value() (driver.Value, error) {
    y, m, d := time.Time(date).Date()
    return time.Date(y, m, d, 0, 0, 0, 0, time.UTC), nil
}

This ensures that dates are timezone-independent, which is the correct behavior for date-only values.

Testing

Added comprehensive tests to verify:

  • Timezone handling works correctly regardless of input timezone
  • Same dates in different timezones produce consistent results
  • All existing functionality remains unchanged

Fixes #309.


💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.

Copilot AI and others added 2 commits September 20, 2025 00:42
Co-authored-by: jinzhu <6843+jinzhu@users.noreply.github.com>
Co-authored-by: jinzhu <6843+jinzhu@users.noreply.github.com>
@Copilot Copilot AI changed the title [WIP] datatypes.Date sends wrong date when postgres.Config{ PreferSimpleProtocol: true } Fix Date timezone handling for PostgreSQL PreferSimpleProtocol Sep 20, 2025
@Copilot Copilot AI requested a review from jinzhu September 20, 2025 00:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

datatypes.Date sends wrong date when postgres.Config{ PreferSimpleProtocol: true }
2 participants