Skip to content

[API Proposal]: method overload DateTimeOffset.Equals(DateTimeOffset other, TimeSpan margin)  #101393

Open
@alexandrehtrb

Description

@alexandrehtrb

Background and motivation

Currently, it is difficult in .NET to compare equality of DateTime(Offset) when parts need to be ignored, such as milliseconds and seconds. Check this Stack Overflow question.

API Proposal

Same for TimeSpan, DateTime and DateTimeOffset. EqualsExact would also have this overload, but considering TimeZoneOffset / DateTimeKind too.

namespace System;

public readonly struct DateTimeOffset
{
    public bool Equals(DateTimeOffset other, TimeSpan margin);
}

API Usage

var dt = DateTime.Parse("Wed, 21 Oct 2015 07:28:00 GMT");
TimeSpan margin1ms = TimeSpan.FromMilliseconds(1.0),
         margin1s = TimeSpan.FromSeconds(1.0),
         margin1min = TimeSpan.FromMinutes(1.0);

if (DateTime.Now.Equals(dt, margin1ms))
{
  Console.WriteLine("Same date and time, up to milliseconds precision");
}
else if (DateTime.Now.Equals(dt, margin1s))
{
  Console.WriteLine("Same date and time, up to seconds precision");
}
else if (DateTime.Now.Equals(dt, margin1min))
{
  Console.WriteLine("Same date and time, up to minutes precision");
}

Alternative Designs

Open for suggestions.

Risks

I don't see any, at first sight.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions