Skip to content

TimeOnly - TimeOnly returns a negative interval instead of wrapping around midnight #4148

Backlog

Description

@CaffeinatedCoder
Environment
PostgreSQL 18.6 (postgres:18), session TimeZone Etc/UTC
.NET 10 runtime 10.0.15, Npgsql.EntityFrameworkCore.PostgreSQL 10.0.4, EF Core 10.0.15, Npgsql 10.0.4
.NET 11 runtime 11.0.0, Npgsql.EntityFrameworkCore.PostgreSQL 11.0.0, EF Core 11.0.0, Npgsql 11.0.0
Also macOS arm64

Both lines print the same output. main at 9a76cd8 has the same code.

Split from #4090 at your request.

In .NET, TimeOnly - TimeOnly wraps around midnight, so the result is always between 0 and 24 hours: 00:30 − 23:00 is 01:30. PostgreSQL's time - time is a signed interval, −22:30.

LINQ Row .NET PostgreSQL SQL
r.Time - r.Late 00:30 − 23:00 01:30:00 −22:30:00 r."Time" - r."Late"
Repro
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

await using var context = new TestContext();
await context.Database.EnsureDeletedAsync();
await context.Database.EnsureCreatedAsync();

context.Rows.Add(new Row { Time = new TimeOnly(0, 30), Late = new TimeOnly(23, 0) });
await context.SaveChangesAsync();
var row = await context.Rows.AsNoTracking().SingleAsync();

// TimeOnly subtraction wraps around midnight in .NET: the result is always between 0 and 24 hours
Console.WriteLine($"TimeOnly 00:30 - 23:00: .NET {row.Time - row.Late}, database {await context.Rows.Select(r => r.Time - r.Late).SingleAsync()}");

public class TestContext : DbContext
{
    public DbSet<Row> Rows => Set<Row>();

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseNpgsql(Environment.GetEnvironmentVariable("Test__Npgsql__DefaultConnection"))
            .LogTo(Console.WriteLine, LogLevel.Information)
            .EnableSensitiveDataLogging();
}

public class Row
{
    public int Id { get; set; }
    public TimeOnly Time { get; set; }
    public TimeOnly Late { get; set; }
}

Output, the same on both lines:

TimeOnly 00:30 - 23:00: .NET 01:30:00, database -22:30:00

The subtraction is NpgsqlSqlExpressionFactory.cs#L477-L499, shared with DateTime, DateOnly and the NodaTime types. For TimeOnly, adding 24 hours when the result is negative (for example CASE WHEN a >= b THEN a - b ELSE a - b + INTERVAL '24 hours' END) matches .NET.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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