Skip to content

Comparing DateTime<Local> with DateTime<Utc> compiles, but should not #1739

@enomado

Description

@enomado

The following code compiles and runs:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=1f4f6369e665294ec58eb4b02bdfc3cc

use chrono;

fn main() {
    let l = chrono::Local::now();
    let u = chrono::Utc::now();
    
    dbg!(l == u);
}

Currently, this works and performs an implicit conversion(or even worse), but I believe it should not be allowed.

May be this?

impl<Tz: TimeZone, Tz2: TimeZone> PartialOrd<DateTime<Tz2>> for DateTime<Tz> {
    /// Compare two DateTimes based on their true time, ignoring time zones

Why this is a problem:

It hides implicit conversions between time zones

Makes it too easy to compare DateTime values from different zones without being explicit

Can lead to subtle bugs when developers accidentally mix local and UTC times

Expected behavior:
The code above should fail to compile, requiring explicit conversion (e.g. l.with_timezone(&Utc) or u.with_timezone(&Local)) before comparison.

Proposal:
Disallow PartialEq, PartialOrd, etc. between DateTime and DateTime when Tz1 != Tz2.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions